c#-具有泛型返回类型的泛型类和方法的委托
作者:互联网
将委托与泛型类一起使用时,会遇到问题.类是泛型的,但方法不是.但是,方法返回类型是泛型类型.
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 };
}
}
此代码引发异常.
更新1:
修复代码以使其易于理解.
例外:
An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module.
Object reference not set to an instance of an object. occurred
解决方法:
问题在这里:
_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), null, createMethod);
overload of .CreateDelegate
you’re using的第二个参数采用该方法所属类型的实例.
您应该使您的方法静态,或创建一个genericType的实例:
var instance = Activator.CreateInstance(genericType);
_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), instance, createMethod);
标签:delegates,c 来源: https://codeday.me/bug/20191108/2008534.html