使用泛型类型保持代码的组织性

本文关键字:代码 组织性 泛型类型 | 更新日期: 2023-09-27 18:17:22

我喜欢在编程时把事情分开。这就是我认为继承很重要的原因之一。

我正在使用一个由我无法修改的类组成的dll文件。dll文件包含ClassA来说明我的例子。

class Program
{
    static void Main(string[] args)
    {
        ClassA object1 = new ClassA();
        SomeMethod<ClassA>(object1 ); // error because " a does not implement ITemp"
    }
    static T SomeMethod<T>(T input)
        where T:ITemp // make sure input has a method MyCustomMethod
    {
        input.MyCustomMethod();
        return input;
    }
     // create this interface so that compiler does not complain when
     // calling MyCustomMethod in method above
    interface ITemp
    {
        void MyCustomMethod();
    }
}

// classA is a sealed class in a dll file that I cannot modify
public class ClassA
{
    public void MyCustomMethod()
    {
    }
}

如果object1没有实现ITemp接口,为什么会出现错误!object1有MyCustomMethod()方法

我知道我可以使用反射来解决这个问题,但我喜欢保持我的代码干净。我还想避免使用动态类型。

使用泛型类型保持代码的组织性

ClassA不实现ITemp接口。仅仅因为它具有与ITemp接口中的方法具有相同名称和签名的方法,并不意味着它实现了该接口。需要声明类才能显式地实现它。

既然你不能扩展ClassA,我能想到的最好的办法就是用一个适配器类型的类来包装它:

public ClassB : ITemp {
    protected ClassA classAInstance;
    public ClassB( ClassA obj ) {
        classAInstance = obj;
    }
    public void MyCustomMethod() {
        classAInstance.MyCustomMethod();
    }
}

然后在你的主方法中:

static void Main(string[] args)
{
    ClassA object1 = new ClassA();
    SomeMethod<ClassB>(new ClassB(object1));
}

您正在尝试使用鸭子键入。除了dynamic类型之外,c#一般不支持这个。ClassA需要实现接口,正如你所指出的,它没有也不能实现接口。您可以用代理包装类,但这可能是一个好主意,也可能不是。