使用反射,我试图从一个无参数构造函数中创建一个委托,如下所示:
Delegate del = GetMethodInfo( () => System.Activator.CreateInstance( type ) ).CreateDelegate( delType );
static MethodInfo GetMethodInfo( Expression<Func<object>> func )
{
    return ((MethodCallExpression)func.Body).Method;
}但我得到了这样的异常:“无法绑定到目标方法,因为它的签名或安全透明度与委托类型的签名或安全透明度不兼容。”什么能行得通?
请注意,至少在这个配置文件中,从.NET的前一个版本开始,CreateDelegate已经被移走了,现在它在MethodInfo上。
发布于 2012-05-15 11:32:21
正如phoog指出的那样,构造函数不会“返回”值;另外,您可以使用ConstructorInfo而不是MethodInfo来获取有关它的信息;这意味着您不能直接围绕它创建一个委托。您必须创建调用构造函数并返回值的代码。例如:
var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null) throw new MissingMethodException("There is no constructor without defined parameters for this object");
DynamicMethod dynamic = new DynamicMethod(string.Empty,
            type,
            Type.EmptyTypes,
            type);
ILGenerator il = dynamic.GetILGenerator();
il.DeclareLocal(type);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
var func = (Func<object>)dynamic.CreateDelegate(typeof(Func<object>));当然,如果您在编译时不知道类型,那么您只能处理Object...
发布于 2018-07-27 14:57:23
试试看:
Dictionary<Type, Delegate> cache = new Dictionary<Type, Delegate>();
public T Create<T>()
{
    if (!cache.TryGetValue(typeof(T), out var d))
        d = cache[typeof(T)]
            = Expression.Lambda<Func<T>>(
                Expression.New(typeof(T)),
                Array.Empty<ParameterExpression>())
            .Compile();
    return ((Func<T>)d)();
}反射非常慢!速度测试在这里(俄语):https://ru.stackoverflow.com/a/860921/218063
发布于 2012-05-15 11:24:41
有一个指向构造函数的委托并不是很有用,因为构造函数没有返回值。委托会构造一个对象,但却不能让你保留对它的引用。
当然,您可以创建返回新构造的对象的委托:
Func<object> theDelegate = () => new object();您还可以从构造函数的ConstructorInfo的Invoke()方法创建委托
对于其他类型的对象:
Func<string> theDelegate = () => new string('w', 3);
Func<SomeClassInMyProject> theDelegate = () => new SomeClassInMyProject();最后一行假设有一个可访问的无参数构造函数。
使用CreateDelegate()更新
T CallConstructor<T>() where T : new() { return new T(); }
Delegate MakeTheDelegate(Type t)
{
    MethodInfo generic = //use your favorite technique to get the MethodInfo for the CallConstructor method
    MethodInfo constructed = generic.MakeGenericMethod(t);
    Type delType = typeof(Func<>).MakeGenericType(t);
    return constructed.CreateDelegate(delType);
}https://stackoverflow.com/questions/10593630
复制相似问题