开发者

Missing MethodInfo for overloaded function with different return type

I have a class defined as follows

inte开发者_开发百科rface ITest   
{  
   List<T> Find<T>(int i);   
}

class Test: ITest  
{  
    public T List<T> Find<T>(int i) { return default(T); }  
    List<T> ITest.Find<T>(int i) { return null; }  
}

When I use typeof(Test).GetMethods() (both with and without appropriate BindingFlags) I do not get the MethodInfo for ITest.Find function. What is the best way of getting the MethodInfo for the missing method?

Thanks


I think you mean the following signature for the first Find method:

public T Find<T>(int i) { return default(T); }

(Your existing declaration doesn't compile; it has two return-types)

I think your issue is that by default, GetMethods doesn't return explicitly-implemented interface methods, which are private. However, it should work fine with these BindingFlags:

BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance

If you want only the two Find methods (and none of the inherited ones), throw in a BindingFlags.DeclaredOnly as well.

E.g.

static void Main(string[] args)
{
    var flags = BindingFlags.NonPublic | BindingFlags.Public |
                BindingFlags.Instance  | BindingFlags.DeclaredOnly;

    foreach(var method in typeof(Test).GetMethods(flags))
         Console.WriteLine(method);
}

Output:

T Find[T](Int32)
System.Collections.Generic.List`1[T] Program.ITest.Find[T](Int32)


Your explicitly implemented ITest.Find method is private. You'll need to use BindingFlags in your GetMethods call:

        var methods = typeof(Test).GetMethods(BindingFlags.Public |
                         BindingFlags.NonPublic | BindingFlags.Instance);


You can use Type.GetInterfaces to get all the interfaces implemented by a type, so the following should get all the methods:

Type t = typeof(Test);

IEnumerable<MethodInfo> methods = t.GetMethods()
    .Concat(t.GetInterfaces().SelectMany(i => i.GetMethods()));


You could use Type.GetInterface, make sure the return value is not null, and then use reflection on the it to get the type. For example:

var @class = typeof(Test);      
var methods = @class.GetMethods();      
PrintMethods("Test", methods);      

methods = @class.GetInterface("ITest", true).GetMethods();
PrintMethods("ITest", methods); 

static void PrintMethods(string typeName, params MethodInfo[] methods)
{
    Console.WriteLine("{0} methods:", typeName);
    foreach(var method in methods)
    {
        Console.WriteLine("{0} returns {1}", method.Name, method.ReturnType);
    }   
}

Outputs (barring my separation space):

Test methods:
Find returns T
ToString returns System.String
Equals returns System.Boolean
GetHashCode returns System.Int32
GetType returns System.Type

ITest methods:
Find returns System.Collections.Generic.List`1[T]

EDIT:

Though Ani's answer seems to solve this for you without the need to resort what is suggested here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜