Ambiguous exception using reflection
Is there a way around this issue?
Take the following code...
namespac开发者_开发技巧e ReflectionResearch
{
class Program
{
static void Main(string[] args)
{
Child child = new Child();
child.GetType().GetProperty("Name");
}
}
public class Parent
{
public string Name
{
get;
set;
}
}
public class Child : Parent
{
public new int Name
{
get;
set;
}
}
}
The line 'child.GetType().GetProperty("Name")' throws b/c Name is ambiguous between Parent and Child. I want "Name" from Child. Is there a way to do this?
I tried various binding flags with no luck.
Add some BindingFlags
:
child.GetType().GetProperty("Name",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
DeclaredOnly
means:
Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.
Or an alternative using LINQ (which makes it easy to add any unusual checks, for example checking Attribute.IsDefined
):
child.GetType().GetProperties().Single(
prop => prop.Name == "Name" && prop.DeclaringType == typeof(Child));
精彩评论