繁体   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