简体   繁体   中英

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.

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.

You should either make your method static, or create an instance of genericType:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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