How can I get my property? Currently an error is occuring of Ambiguous match found
, see the comment line in code.
public class MyBaseEntity
{
public MyBaseEntity MyEntity { get; set; }
}
public class MyDerivedEntity : MyBaseEntity
{
public new MyDerivedEntity MyEntity { get; set; }
}
private static void Main(string[] args)
{
MyDerivedEntity myDE = new MyDerivedEntity();
PropertyInfo propInfoSrcObj = myDE.GetType().GetProperty("MyEntity");
//-- ERROR: Ambiguous match found
}
Type.GetProperty
Situations in which AmbiguousMatchException occurs ...
...derived type declares a property that hides an inherited property with the same name, by using the new modifier
If you run the following
var properties = myDE.GetType().GetProperties().Where(p => p.Name == "MyEntity");
you will see that two PropertyInfo
objects are returned. One for MyBaseEntity
and one for MyDerivedEntity
. That is why you are receiving the Ambiguous match found error.
You can get the PropertyInfo
for MyDerivedEntity
like this:
PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p =>
p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));
For property:
MemberInfo property = myDE.GetProperty(
"MyEntity",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
For method:
MemberInfo method = typeof(String).GetMethod(
"ToString",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly,
null,
new Type[] { },// Method ToString() without parameters
null);
BindingFlags.DeclaredOnly - Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With