【问题标题】:using Explicit Interface Implementation使用显式接口实现
【发布时间】:2012-03-29 06:49:48
【问题描述】:

我正在尝试使用显式接口实现来更改接口实现类中的属性类型。

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

谢谢

【问题讨论】:

    标签: c# interface


    【解决方案1】:

    那是因为你已经接收到对象作为接口,所以它不知道类的新属性类型。您需要:

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

    一个更好的解决方案可能是使用visitor 模式 - 这将具有处理不同 ISample 的实现。

    【讨论】:

    • 第二个示例不起作用,因为SomeClass1 是属性的类型而不是ISample 的类型,如果ISample 属于SampleA,第一个示例将引发异常
    • 然后使用约束:) 我假设事情是公开的,他的代码显示它不是公开的。
    • 我为 ntziolis 添加了一些类型检查 - 我没有展示安全路线,我展示了如何投射对象。显然,应该添加一些设计以使代码更可靠。
    • @user1299340 - 我得到答案了吗?!?! [一直在争取更多的 SO 点数]
    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多