我对这段代码有疑问:
public static Delegate[] ExtractMethods(object obj)
{
Type type = obj.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
Delegate[] methodsDelegate = new Delegate[methods.Count()];
for (int i = 0; i < methods.Count(); i++)
{
methodsDelegate[i] = Delegate.CreateDelegate(null, methods[i]);
}
return methodsDelegate;
}
Run Code Online (Sandbox Code Playgroud)
在Delegate.CreateDelegate委托类型中最受驱动,但我为多个对象调用此方法。如何获取委托类型?
我正在尝试从具有输出参数的 MethodInfo 对象获取委托。我的代码如下:
static void Main(string[] args) {
MethodInfo m = typeof(Program).GetMethod("MyMethod2");
IEnumerable<Type> paramsTypes = m.GetParameters().Select(p => p.ParameterType);
Type methodType = Expression.GetDelegateType(paramsTypes.Append(m.ReturnType).ToArray());
Delegate d = m.CreateDelegate(methodType);
Action a = (Action)d;
a();
}
Run Code Online (Sandbox Code Playgroud)
我得到的是 System.InvalidCastException: Unable to cast object of type Delegate2$1 to type System.Action in the line that do "Action a = (Action)d". 问题是我不知道在 Action 中放入什么类型,因为我知道正确的类型不是 String,它是编译中 String (String&) 的 Output 等价物。
MyMethod2 有一个输出参数,我认为这就是问题所在,因为当我使用 MyMethod 作为输入参数测试它时,它可以工作。
public static void MyMethod2(out String outputParameter) {
outputParameter = "hey";
}
public static void …Run Code Online (Sandbox Code Playgroud)