Joh*_*ore 3 .net c# reflection
有没有解决这个问题的方法?
请参考以下代码......
namespace 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
行'child.GetType().GetProperty("Name")'抛出b/c名称在父和子之间是不明确的.我想要来自Child的"姓名".有没有办法做到这一点?
我尝试了各种绑定标志,没有运气.
添加一些BindingFlags:
child.GetType().GetProperty("Name",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)
DeclaredOnly 手段:
指定仅应考虑在提供的类型的层次结构级别声明的成员.不考虑继承的成员.
或者使用LINQ的替代方法(这使得添加任何异常检查变得容易,例如检查Attribute.IsDefined):
child.GetType().GetProperties().Single(
prop => prop.Name == "Name" && prop.DeclaringType == typeof(Child));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |