seb*_*ebf 4 .net c# oop design-patterns interface
以下代码显示了我想要做的事情; 也就是说,我想约束anObject,以便它可以用作使用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
}
Run Code Online (Sandbox Code Playgroud)
但是这个例子失败了,因为IInterfaceOneAndTwo本身就是一个接口,而Implementation并没有实现它.
我知道如果我使用泛型我可以约束它们,但我想知道,如果有一种方法可以做到这一点没有泛型?
有没有办法说anObject应执行IInterfaceOne与IInterfaceTwo不使用IInterfaceOneAndTwo?
不是你现在的方式.只有通用约束才具有这种能力.
您可以重写它以使用泛型:
public class UsingImplementation<T>
where T : IInterface1, IInterface2, new()
{
T anObject = new T();
void SomeMethod() {
anObject.MethodFromInterface1();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |