简体   繁体   English

使用显式接口实现

[英]using Explicit Interface Implementation

I am trying to change the property type in interface implementation class 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;    
}

But when I need to pass in interface obj in a function, I cant access the objects of SomeClass1 or SomeClass2. 但是当我需要在函数中传入接口obj时,我无法访问SomeClass1或SomeClass2的对象。

For eg: 例如:

public void MethodA(ISample sample)    
{    
  string str = sample.Value.s1;//doesnt work.How can I access s1 using ISample??    
}

I don't know if this is understandable, but I cant seem to get an easier way to explain this. 我不知道这是否可以理解,但我似乎无法更容易地解释这一点。 Is there a way to access the properties of SomeClass1 using interface ISample? 有没有办法使用接口ISample访问SomeClass1的属性?

Thanks 谢谢

That is because you've received the object as the interface, so it doesn't know about the class's new property type. 那是因为你已经收到了对象作为接口,所以它不知道类的新属性类型。 You would need to: 你需要:

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

A better solution might be to use the visitor pattern - which would have implementations for handling the different ISample's. 一个更好的解决方案可能是使用访问者模式 - 这将具有处理不同ISample的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM