taf*_*afa 16 c# propertyinfo .net-3.5
如在.NET Reflection中设想私有属性一样,可以使用私有setter设置属性.但是当在基类中定义属性时,抛出System.ArgumentException:"找不到属性集方法".
一个例子可以是:
using System;
class Test
{
public DateTime ModifiedOn { get; private set;}
}
class Derived : Test
{
}
static class Program
{
static void Main()
{
Derived p = new Derived ();
typeof(Derived).GetProperty("ModifiedOn").SetValue(
p, DateTime.Today, null);
Console.WriteLine(p.ModifiedOn);
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道解决这种情况的方法?
编辑:给出的示例是问题的简单说明.在现实世界的场景中,我不知道属性是在基类中定义的,还是在基类的基础中定义的.
Pau*_*ant 20
我有一个类似的问题,我的私有财产在基类中声明.我使用DeclaringType来获取定义属性的类的句柄.
using System;
class Test
{
public DateTime ModifiedOn { get; private set;}
}
class Derived : Test
{
}
static class Program
{
static void Main()
{
Derived p = new Derived ();
PropertyInfo property = p.GetType().GetProperty("ModifiedOn");
PropertyInfo goodProperty = property.DeclaringType.GetProperty("ModifiedOn");
goodProperty.SetValue(p, DateTime.Today, null);
Console.WriteLine(p.ModifiedOn);
}
}
Run Code Online (Sandbox Code Playgroud)
Not*_*ple 10
我认为这会奏效:
using System;
class Test
{
public DateTime ModifiedOn { get; private set;}
}
class Derived : Test
{
}
static class Program
{
static void Main()
{
Derived p = new Derived ();
typeof(Test).GetProperty("ModifiedOn").SetValue(
p, DateTime.Today, null);
Console.WriteLine(p.ModifiedOn);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要从实际定义的类而不是派生类中获取属性定义
编辑:
要在任何基类上选择它,您需要在所有父类中查找它.
这样的东西然后递归到基类,直到你碰到物体或找到你的财产
typeof(Derived ).GetProperties().Contains(p=>p.Name == "whatever")
Run Code Online (Sandbox Code Playgroud)
除了@ LukeMcGregor之外,另一个选择是使用BaseType
typeof(Derived)
.BaseType.GetProperty("ModifiedOn")
.SetValue(p, DateTime.Today, null);
Run Code Online (Sandbox Code Playgroud)
我做了这个可重用的方法.它处理我的场景.
private static void SetPropertyValue(object parent, string propertyName, object value)
{
var inherType = parent.GetType();
while (inherType != null)
{
PropertyInfo propToSet = inherType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
if (propToSet != null && propToSet.CanWrite)
{
propToSet.SetValue(parent, value, null);
break;
}
inherType = inherType.BaseType;
}
}
Run Code Online (Sandbox Code Playgroud)