c# - 可以将接口(interface)添加到现有的 .NET 类型吗?

标签 c# type-conversion

我下面的示例涉及 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() }

谢谢, 助理设计师

最佳答案

有一些涉及创造性思维的方法可以解决这个问题。

最明显的:

Adapter Pattern

您构建接口(interface),然后构建两个适配器,每个适配器采用 NetClassA,另一个采用 NetClassB。您的通用代码保持通用,特定的代码存在于适配器中。

这甚至适用于密封类。您不从 NetClassA 或 NetClassB 获得服务。我有点想把这个留给你来弄清楚实现,如果你想要代码实现,我会在一天后回来。

其他要看的东西:

Extension Methods

和/或

Reflection

更多帮助

             =====================
             = ICommonNetMethods =
             =====================
                       | (derive)
         |-------------------------------|
====================            ====================
= NetClassAAdapter =            = NetClassBAdapter =
====================            ====================
         | uses (not derive)             | uses (not derive)
   =============                   =============
   = NetClassA =                   = NetClassB =
   =============                   =============

关于c# - 可以将接口(interface)添加到现有的 .NET 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930739/

相关文章:

c# - 动态转换为通用类型

c# - GUI Winform 和结束/终止进程

java - 是什么导致了 "Incompatible operand types"错误?

c# - 在列表 dataTemplate xaml 中绑定(bind)项目本身

c# - 命名空间结合 TFS/Source Control 解释

c++ - 为什么在这种情况下没有调用最合适的构造函数?

arrays - 在 VB.NET 中将字符串数组转换为 double 组

python - 在 Python 中将 int 赋值给变量是什么意思?

c# - Web API 请求的滑动 session

c# - 设置元 :resourcekey on page load