我有以下代码:
public class Ancestor
{
public string Property {get; protected set;}
}
public class Base : Ancestor
{
public string Property {get; set;}
}
public class Derived : Base
{
public Derived(string message)
{
//I need both properties to have the message value
}
}
Ancestor和Base类不是我的代码,我无法改变它们
有没有办法将Ancestor的属性设置为消息的值?
显然,简单地执行以下操作将无法正常工作
Ancestor ancestor = this;
ancestor.Property = message
因为setter受到保护。
答案 0 :(得分:3)
仅通过反思:
public class Derived : Base
{
public Derived(string message)
{
Type type = typeof(Ancestor);
Ancestor a = (Ancestor)this;
type.GetProperty("Property").SetMethod.Invoke(a, new[] { message });
}
}
答案 1 :(得分:1)
我找到了满足我需求的解决方案。 我的Ancestor类来自一个接口:
public interface IAncestor
{
string Property { get; }
}
我所做的是使用显式接口声明,如下所示:
public class Derived : Base, IAncestor
{
public Derived(string message)
{
Property = message;
base.Property = message;
}
string IAncestor.Property{get { return Property; }}
}
现在接下来的测试通过了:
[TestMethod]
public void ValidatePropertyIsFullyPopulated()
{
const string expectedMessage = "hello!";
var derived = new Derived(expectedMessage);
Base baseClass = derived;
IAncestor ancestor = derived;
Assert.AreEqual(expectedMessage, derived.Property);
Assert.AreEqual(expectedMessage, baseClass.Property);
Assert.AreEqual(expectedMessage, ancestor.Property);
//Notice that this Assert WILL fail because Ancestor.Property is
//not marked as virtual.
Ancestor ancestorClass = derived;
//Assert.AreEqual(expectedMessage, ancestorClass.Property);
}