c# - 我可以在没有泛型的情况下定义/约束成员实现两个接口(interface)吗?

标签 c# .net oop design-patterns interface

下面的代码展示了我想要做什么;也就是说,我想约束一个对象,以便它可以用作各种使用 IInterfaceOne 或 IInterfaceTwo 的方法的参数,其中两者都不从另一个继承。

public interface IInterfaceOne { }
public interface IInterfaceTwo { }

public class Implementation : IInterfaceOne, IInterfaceTwo
{
}

public interface IInterfaceOneAndTwo : IInterfaceOne, IInterfaceTwo { }

public class UsingImplementation
{
    IInterfaceOneAndTwo anObject = (IInterfaceOneAndTwo)(new Implementation()); //fails because Implementation doesnt acctually implement IInterfaceOneAndTwo
}

但是这个例子失败了,因为 IInterfaceOneAndTwo 本身就是一个接口(interface),而实现并没有实现它。

我知道如果我使用泛型我可以限制它们,但我想知道,是否有一种方法可以在没有泛型的情况下做到这一点?

有没有办法说 anObject 应该实现 IInterfaceOneIInterfaceTwo,而不使用 IInterfaceOneAndTwo ?

最佳答案

不是你现在的样子。只有通用约束具有这种能力。

您可以重写它以使用泛型:

public class UsingImplementation<T>
   where T : IInterface1, IInterface2, new()
{
    T anObject = new T();

    void SomeMethod() {
       anObject.MethodFromInterface1();
    }
}

关于c# - 我可以在没有泛型的情况下定义/约束成员实现两个接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9037577/

相关文章:

c# - 如何使用 Assert.Throws 断言异常类型?

c# - 使用代理开发服务器时,.net core spa 模板应用程序中 "Fetch data"上出现 404

c# - ReportViewer 报告到 PDF 文件

c++ - 在 C++ 中,如何使同一类的两个对象具有独特的函数行为?

JavaScript - this.update 不是函数

c# - 如何对通用接口(interface)使用依赖注入(inject)?

c# - 如何使用选定字段将 IEnumerable 转换为匿名类型

.net - 在 XElement 中获取空格

c# - 如何在不丢失任何数据的情况下序列化和反序列化异常对象?

Perl:将 Coderef 分配给方法而不使用符号表 Hack