我下面的示例涉及2个.NET类,它们都包含方法CommonMethod。 我想设计MyMethod,可以接受任何一个类(使用)同时保留NetClassA和NetClassB的公共功能。 Case1本应实现这一点,但是如下所述是非法的。 Case2也可以完成目标,但是INetClassA和INetClassB不存在。 因此,我的问题是是否有一种方法可以在现有的.NET类型上强制实施自定义接口(ICommonNetMethods)(情况3)? 欢迎提供解决方案以解决我的问题。
// Case 1: Illegal because "where" can only have 1 base class
public void MyMethod<Ttype>(Ttype myClass) where Ttype : NetClassA, NetClassB {}
// Case 2: Legal to utlize multiple "where" interface types
public void MyMethod<Ttype>(Ttype myClass) where Ttype : INetClassA, INetClassB {}
// Case 3: For this to work ICommonNetMethods must be added to NetClassA/NetClassB
public void MyMethod<Ttype>(Ttype myClass) where Ttype : ICommonNetMethods {}
NetClassA() { This .NET class has method CommonMethod() }
NetClassB() { This .NET class has method CommonMethod() }
interface ICommonNetMethods { void CommonMethod() }
感谢,aidesigner