3
我想要使用顯式接口實現更改接口實現類中的屬性類型。使用顯式接口實現
interface ISample
{
object Value { get; set; }
}
class SampleA : ISample
{
SomeClass1 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass1)value; }
}
}
class SampleB : ISample
{
SomeClass2 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass2)value; }
}
}
class SomeClass1
{
string s1;
string s2;
}
但是當我需要在函數中傳入接口obj時,我不能訪問SomeClass1或SomeClass2的對象。
對於如:
public void MethodA(ISample sample)
{
string str = sample.Value.s1;//doesnt work.How can I access s1 using ISample??
}
我不知道這是可以理解的,但我不能似乎得到一個更簡單的方法來解釋這個問題。有沒有辦法使用接口ISample訪問SomeClass1的屬性?
感謝
第二個例子不起作用,因爲'SomeClass1'是屬性的類型而不是'ISample'的類型,如果'Sample'是'SampleA' – ntziolis 2012-03-28 22:39:58
則第一個將拋出異常,然後使用約束:)和I假設事情是公開的,他的代碼顯示它不公開。 – payo 2012-03-28 22:41:51
我爲ntziolis添加了一些類型檢查 - 我沒有顯示安全路線,我正在展示如何投射物體。顯然,應該添加一些設計以使代碼更加可靠。 – payo 2012-03-28 22:48:10