2010-03-10 32 views
12

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ỏ.

Trả lời

8

Bạn phương pháp không phải là một phương pháp tĩnh, vì vậy bạn cần phải sử dụng:

Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi); 

Đi qua "này" để đối số thứ hai sẽ cho phép phương pháp này bị ràng buộc với phương pháp dụ trên đối tượng hiện hành. ..

+0

Doh! Cảm ơn một nhóm - không biết làm thế nào tôi bỏ lỡ điều đó. – Dathan

Các vấn đề liên quan