简体   繁体   English

使用泛型返回类型委托泛型类和方法

[英]Delegate for generic class and method with generic return type

When using delegate with generic classes, have an issue. 使用带有泛型类的委托时,会出现问题。 Class is generic but method is not. 类是通用的,但方法不是。 However method return type is generic type. 但是方法返回类型是泛型类型。

public abstract class BaseEntity {
    public DateTime CreateDateTime { get; set; } = DateTime.Now;
    public long CreateUserId { get; set; }
}

public class ClassA : BaseEntity {

}

class Program {
    private delegate object MyDelegate(long id);
    private static MyDelegate _myHandler;

    static void Main(string[] args) {
        var genericType = typeof(TestClass<>).MakeGenericType(typeof(ClassA));
        var createMethod = genericType.GetMethod("CreateEntity");
        _myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), null, createMethod);

        var result = _myHandler(5);
    }
}

class TestClass<T> where T : BaseEntity, new() {
    public T CreateEntity(long userId) {
        return new T() { CreateUserId = userId };
    }
}

This code throw exception. 此代码抛出异常。

Update 1: Fix the code to be understandable. 更新1:修复代码以使其易于理解。

Exception: 例外:

An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module.
Object reference not set to an instance of an object. occurred

The issue is here: 问题在于:

_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), null, createMethod);

The second parameter of the overload of .CreateDelegate you're using takes an instance of the type to which the method belongs. 您正在使用的.CreateDelegate重载的第二个参数采用该方法所属类型的实例。

You should either make your method static, or create an instance of genericType: 您应该使方法静态,或者创建genericType的实例:

var instance = Activator.CreateInstance(genericType);
_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), instance, createMethod);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM