首先我要说的是,我很清楚这样做的危险,并且100%理解这是一个“坏主意”......但是......
如何从基类设置派生类属性?
public class Foo
{
public void SetSomeValue(int someParam)
{
var propertyInfo = this.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(t => t.Name == "SomeValue")
.First();
propertyInfo.SetValue(null, someParam); // <-- This shouldn't be null
}
}
public class Bar : Foo
{
public int SomeValue { get; set; }
}
如何调用属性值以调用SetValue?
编辑:
实际上这很容易。卫生署。
propertyInfo.SetValue(this, someParam);
答案 0 :(得分:0)
propertyInfo.SetValue(this, someParam);
答案 1 :(得分:0)
<强>用法:强>
var bar = new Bar {SomeValue = 10};
bar.SetSomeValue(20);
Console.WriteLine(bar.SomeValue); // Should be 20
<强>声明:强>
public class Foo
{
public void SetSomeValue(int someParam)
{
var propertyInfo = this.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public).First(t => t.Name == "SomeValue");
propertyInfo.SetValue(this, someParam, null);
}
}
public class Bar : Foo
{
public int SomeValue
{
get;
set;
}
}
答案 2 :(得分:-1)
你可以摆弄界面。这样,您至少可以耦合到接口而不是实际的派生类。
public class Foo {
public void SetSomeValue(int someParam) {
if (this is ISomeValueHolder) {
((ISomeValueHolder)this).SomeValue = someParam;
}
}
}
public interface ISomeValueHolder {
int SomeValue { get; set; }
}
public class Bar : Foo, ISomeValueHolder {
public int SomeValue { get; set; }
}