首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中将接口实现委托给其他类

在C#中,将接口实现委托给其他类的方法是通过使用代理类。代理类实现了接口,并将接口方法的实现委托给其他类。以下是一个简单的示例:

首先,定义一个接口:

代码语言:csharp
复制
public interface IMyInterface
{
    void MyMethod();
}

然后,创建一个代理类,实现接口并将实现委托给其他类:

代码语言:csharp
复制
public class MyInterfaceProxy : IMyInterface
{
    private readonly MyOtherClass _myOtherClass;

    public MyInterfaceProxy(MyOtherClass myOtherClass)
    {
        _myOtherClass = myOtherClass;
    }

    public void MyMethod()
    {
        _myOtherClass.MyMethod();
    }
}

接下来,创建一个实现了接口的类:

代码语言:csharp
复制
public class MyOtherClass
{
    public void MyMethod()
    {
        Console.WriteLine("MyMethod called in MyOtherClass");
    }
}

最后,在主程序中使用代理类:

代码语言:csharp
复制
public static void Main(string[] args)
{
    MyOtherClass myOtherClass = new MyOtherClass();
    MyInterfaceProxy proxy = new MyInterfaceProxy(myOtherClass);

    proxy.MyMethod();
}

在这个示例中,MyInterfaceProxy 类实现了 IMyInterface 接口,并将 MyMethod 方法的实现委托给了 MyOtherClass 类。当我们调用 proxy.MyMethod() 时,实际上是调用了 MyOtherClass 类的 MyMethod 方法。

这种方法可以让我们在不修改原始类的情况下,实现接口的委托。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券