相关疑难解决方法(0)

C# 从 MethodInfo 获取委托

我对这段代码有疑问:

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委托类型中最受驱动,但我为多个对象调用此方法。如何获取委托类型?

c# delegates types

2
推荐指数
1
解决办法
2727
查看次数

使用输出参数从 MethodInfo 创建委托,无需动态调用

我正在尝试从具有输出参数的 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)

.net c# reflection lambda delegates

1
推荐指数
1
解决办法
167
查看次数

标签 统计

c# ×2

delegates ×2

.net ×1

lambda ×1

reflection ×1

types ×1