我没有类型的源代码,需要使用内部参数调用内部方法。
有没有办法做这样的事情:Set.InOrderTreeWalk((object o) => o != null)
?
namespace assembly_1
{
internal delegate bool TreeWalkPredicate<T>(Set<T>.Node node);
public class Set<T>
{
private Node[] nodes;
internal bool InOrderTreeWalk(TreeWalkPredicate<T> action)
{
foreach (var node in nodes)
{
if (!action(node))
return false;
}
return true;
}
internal class Node
{
public T Item;
}
}
}
在我进入它之前,插入关于实现细节如何在内部出于某种原因的标准免责声明,如果某些内容发生变化并且破坏了您的反射代码,作者不欠您解释。
从表面上看,参数是内部委托类型的事实确实让这有点麻烦,但实际上有一种方便的方法来获取它:获取MethodInfo
我们要调用的方法的 ,然后检查它的参数。
让我们假设我们已经有了这个变量,并分配了一个实例:
Set<MyNode> set;
...并且该MyNode
类型已在某处声明。我们要Set<MyNode>.InOrderTreeWalk
为集合中的每个节点调用以下方法:
private bool MyPredicate(Set<MyNode>.Node node)
{
return true;
}
没有太多内容,只需按照评论进行操作:
// Get the method we want to call.
MethodInfo inOrderTreeWalkMethod = set.GetType().GetMethod(
"InOrderTreeWalk", BindingFlags.NonPublic | BindingFlags.Instance);
// Get the internal delegate type from the parameter info. The type retrieved here
// is already close-constructed so we don't have to do any generic-related manipulation.
Type treeWalkPredicateType = inOrderTreeWalkMethod.GetParameters()[0].ParameterType;
// Get the method we want to be called for each node.
MethodInfo myPredicateMethod = GetType().GetMethod(
nameof(MyPredicate), BindingFlags.NonPublic | BindingFlags.Instance);
// Create the delegate. This is where the magic happens. The runtime validates
// type compatibility and throws an exception if something's wrong.
Delegate myPredicateDelegate = myPredicateMethod.CreateDelegate(treeWalkPredicateType, this);
// Call the internal method and pass our delegate.
bool result = (bool)inOrderTreeWalkMethod.Invoke(set, new object[] { myPredicateDelegate });
假设您已经提供了有关您正在使用的组件的足够信息,并且除非信任级别存在任何问题,否则应该这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句