下面的代码展示了我想要做什么;也就是说,我想约束一个对象,以便它可以用作各种使用 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
应该实现 IInterfaceOne
和 IInterfaceTwo
,而不使用 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/