.NET: Using reflection how can I tell if a property is shadowing another property? [duplicate]
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;
}
精彩评论