2015-01-27 3 views
0

У меня есть следующий код:Установка свойства скрытой базы базового класса

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 значение сообщения?
Очевидно просто делать что-то вроде следующего не будет работать

Ancestor ancestor = this; 
ancestor.Property = message 

, потому что сеттер защищен.

+0

Нет, я не может легко увидеть какой-либо способ сделать это. По сути, дизайн нарушен, и автору «Базы» следует спросить, почему они сделали такую ​​неприятную вещь ... –

+1

Вы можете взломать стоимость недвижимости через Reflection –

ответ

0

Я нашел решение, которое удовлетворяет мои потребности. Мой класс предок происходит от интерфейса:

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); 
} 
3

через Reflection только:

public class Derived : Base 
{ 
    public Derived(string message) 
    { 
     Type type = typeof(Ancestor); 
     Ancestor a = (Ancestor)this; 
     type.GetProperty("Property").SetMethod.Invoke(a, new[] { message }); 
    } 
} 
+3

, но это безумие! –

+0

Да, это то, что я думал ... – atlanteh

Смежные вопросы