我下面的示例涉及 2 个 NET 类,它们都包含 CommonMethod 方法。我想设计的 MyMethod 可以接受任一类 (Using),同时保留 NetClassA 和 NetClassB 共有的功能。 Case1 会这样做,只是它是非法的,如下所述。除了 INetClassA 和 INetClassB 不存在之外,案例 2 也将实现目标。因此,我的问题是有没有一种方法可以对现有的 .NET 类型(案例 3)强加自定义接口(interface)(ICommonNetMethods)?欢迎使用替代解决方案来解决我的问题。
// 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() }
谢谢, 助理设计师
最佳答案
有一些涉及创造性思维的方法可以解决这个问题。
最明显的:
您构建接口(interface),然后构建两个适配器,每个适配器采用 NetClassA,另一个采用 NetClassB。您的通用代码保持通用,特定的代码存在于适配器中。
这甚至适用于密封类。您不从 NetClassA 或 NetClassB 获得服务。我有点想把这个留给你来弄清楚实现,如果你想要代码实现,我会在一天后回来。
其他要看的东西:
和/或
更多帮助
=====================
= ICommonNetMethods =
=====================
| (derive)
|-------------------------------|
==================== ====================
= NetClassAAdapter = = NetClassBAdapter =
==================== ====================
| uses (not derive) | uses (not derive)
============= =============
= NetClassA = = NetClassB =
============= =============
关于c# - 可以将接口(interface)添加到现有的 .NET 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930739/