有没有办法绕过这个问题?
使用下面的代码...
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;
}
}
}行'child.GetType().GetProperty(" Name ")‘抛出b/c名称在父项和子项之间不明确。我想从孩子那里得到“名字”。有没有办法做到这一点?
我尝试了各种绑定标志,但都没有成功。
发布于 2010-11-11 14:09:36
添加一些BindingFlags
child.GetType().GetProperty("Name",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);DeclaredOnly的意思是:
指定只应考虑在所提供类型的层次结构级别上声明的成员。继承的成员不被考虑。
或者使用LINQ (这使得添加任何不寻常的检查,例如检查Attribute.IsDefined)变得容易:
child.GetType().GetProperties().Single(
prop => prop.Name == "Name" && prop.DeclaringType == typeof(Child));https://stackoverflow.com/questions/4151794
复制相似问题