c# - 使用成员作为实现者实现接口(interface)

标签 c# .net

我有实现 IA 的 A 类。
现在我需要创建也应该实现 IA 的 B 类。 B 类具有 A 类的实例作为成员。

有什么方法可以定义A的实例实现类B中的IA吗?

interfase IA {
    void method1();
    void method2();
    .
    .
    .
    .
    void methodN();
}

class A:IA {
    public void method1(){}
    public void method2(){}
    .
    .
    .
    .
    public void methodN(){}
}

class B:IA {
    private IA m_a;
    public B(IA a) {
      m_a=a;
    }

    //Instead all of this I am looking of a way to define that m_a is the implement to IA of B
    public void method1(){ use of a.method1 }
    public void method2(){ use of a.method2 }
    .
    .
    .
    .
    public void methodN(){ use of a.methodN }
}

最佳答案

不一定,您可能想要定义某种返回 IA 成员的接口(interface),例如 Enumerable/Enumerator 图案。

public interface IB
{
   public IA Item { get; }
}

然后 B 可以简单地返回您存储在其中的实例。

public class B : IB
{
    public IA Item { get; private set; }
}

A 甚至可以实现 IB

public class A : IA, IB
{
    public void Method1();
    //...
    public void MethodN();

    IA IB.Item
    {
        get
        {
            return this;
        }
    }
}

关于c# - 使用成员作为实现者实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6262315/

相关文章:

c# - WPF 将文本框绑定(bind)到 ViewModel

c# - MVC ajax 形式的嵌套对象在 Controller 中捕获

c# - 仅引用 csvhelper 中的字符串

c# - 如何管理在运行时创建的 WinForms 按钮的委托(delegate)?

c# - 从 List<> 获取特定项目

c# - 从 TypeBuilder.CreateType 返回的类型的 Activator.CreateInstance 抛出 ArgumentException

c# - User32.dll ToUnicodeEx函数的使用

c# - 如何在调用 DBSet<T>.Find(id) 时使 EF Code First 加载 "ICollection"属性

c# - 如何从 FTP 获取文件(使用 C#)?

c# - 如何在 .net 3.5 中使用 SignalR