Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

inheritance - C# GetMethod doesn't return a parent method

I have the following class tree:

public class A
{
    public static object GetMe(SomeOtherClass something)
    {
        return something.Foo();
    }
}

public class B:A
{
    public static new object GetMe(SomeOtherClass something)
    {
        return something.Bar();
    }
}

public class C:B
{

}

public class SomeOtherClass
{

}

Given SomeOtherClass parameter = new SomeOtherClass()) this works:

typeof(B).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter));

But this:

typeof(C).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter));

throws a NullReferenceException, while I wish it would call the exact same method than above.

I've tried several binding flags to no avail. Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use one the overloads taking a BindingFlags parameter, and include FlattenHierarchy.

Specifies that public and protected static members up the hierarchy should be returned. Private static members in inherited classes are not returned. Static members include fields, methods, events, and properties. Nested types are not returned.

(Edited to remove the point about private static methods, now the question has been changed to make them public.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...