簡體   English   中英

使用顯式接口實現

[英]using Explicit Interface Implementation

我試圖使用顯式接口實現更改接口實現類中的屬性類型。

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的屬性?

謝謝

那是因為你已經收到了對象作為接口,所以它不知道類的新屬性類型。 你需要:

public void MethodA(ISample sample)
{
  if (sample is SampleA)
  {
    string str = ((SampleA)sample).Value.s1;
  }     
}

一個更好的解決方案可能是使用訪問者模式 - 這將具有處理不同ISample的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM