Val*_*mas 30 c# reflection system.reflection
我如何获得我的财产?目前发生错误Ambiguous match found
,请参阅代码中的注释行.
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
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*mey 35
出现AmbiguousMatchException的情况......
...派生类型声明一个属性,该属性使用new修饰符隐藏具有相同名称的继承属性
如果您运行以下
var properties = myDE.GetType().GetProperties().Where(p => p.Name == "MyEntity");
Run Code Online (Sandbox Code Playgroud)
你会看到PropertyInfo
返回两个对象.一个为MyBaseEntity
一个为一个MyDerivedEntity
.这就是您收到Ambiguous match found错误的原因.
你可以得到PropertyInfo
的MyDerivedEntity
是这样的:
PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p =>
p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));
Run Code Online (Sandbox Code Playgroud)
Alp*_*ega 25
对于财产:
MemberInfo property = myDE.GetProperty(
"MyEntity",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
Run Code Online (Sandbox Code Playgroud)
方法:
MemberInfo method = typeof(String).GetMethod(
"ToString",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly,
null,
new Type[] { },// Method ToString() without parameters
null);
Run Code Online (Sandbox Code Playgroud)
BindingFlags .DeclaredOnly - 指定只应考虑在提供的类型的层次结构级别声明的成员.不考虑继承的成员.
Cha*_*ehn 13
由于new
声明中出现歧义MyDerivedEntity
.为了克服这个问题,您可以使用LINQ:
var type = myObject.GetType();
var colName = "MyEntity";
var all = type.GetProperties().Where(x => x.Name == colName);
var info = all.FirstOrDefault(x => x.DeclaringType == type) ?? all.First();
Run Code Online (Sandbox Code Playgroud)
这将从派生类型中获取属性(如果存在),否则为基础.如果需要,这可以很容易地翻转.
Kevin已经指出了这个问题,但你不需要复杂的语句或LINQ:
PropertyInfo propInfoSrcObj = myDE.GetType().
GetProperty("MyEntity", typeof(MyDerivedEntity));
Run Code Online (Sandbox Code Playgroud)