开发者

.NET: Using reflection how can I tell if a property is shadowing another property? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Du开发者_开发知识库plicate:

How does reflection tell me when a property is hiding an inherited member with the 'new' keyword?

Using reflection how can I tell if a property is shadowing another property? I am working on some code generation and I need that information to call said properties correctly.

Exmaple:

class A{
    int Foo {get;set;}
}

class B:A{
    string new Foo {get;set;}
}

Code I would need to generate:

someB.Foo = "";
((A)someB).Foo = 0;


There weren't any answers marked as correct in the duplicate so I copied the one that seems to work after minor corrections.

    public static bool IsHidingMember(PropertyInfo self)
    {
        Type baseType = self.DeclaringType.BaseType;
        if (baseType == null)
            return false;

        PropertyInfo baseProperty = baseType.GetProperty(self.Name);

        if (baseProperty == null)
        {
            return false;
        }

        if (baseProperty.DeclaringType == self.DeclaringType)
        {
            return false;
        }

        var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();
        var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();

        return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜