Tôi có đoạn mã sau:Tạo đại biểu generic sử dụng phản ánh
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
// works
Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>);
MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) });
// throws ArgumentException: Error binding to target method
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi);
}
public IEnumerable<int> SomeMethod<T>()
{
return new int[0];
}
}
Tại sao tôi không thể tạo ra một đại biểu cho phương thức chung của tôi? Tôi biết tôi chỉ có thể sử dụng mi.Invoke(this, null)
, nhưng vì tôi sẽ muốn thực thi SomeMethod
có khả năng vài triệu lần, tôi muốn có thể tạo đại biểu và lưu trữ bộ nhớ cache dưới dạng tối ưu hóa nhỏ.
Doh! Cảm ơn một nhóm - không biết làm thế nào tôi bỏ lỡ điều đó. – Dathan