我可以创建一种接口类型的通用方法吗?

时间:2010-03-26 22:21:50

标签: c# generics

是否可以使用

之类的签名创建通用方法
public static string MyMethod<IMyTypeOfInterface>(object dataToPassToInterface)
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

我是否必须使用(T)Activator.CreateInstance();

创建界面

4 个答案:

答案 0 :(得分:5)

如果你想创建一个实现接口的某种类型的新实例并传递一些数据,你可以这样做:

public static string MyMethod<T>(object dataToPassToInterface) where T : IMyTypeOfInterface, new()
{
    T instance = new T();
    return instance.HandleData(dataToPassToInterface);
}

并将其称为:

string s = MyMethod<ClassImplementingIMyTypeOfInterface>(data);

答案 1 :(得分:2)

您无法实例化接口。您只能实例化实现该接口的类。

答案 2 :(得分:1)

您可以将type参数约束为实现IMyTypeOfInterface的东西:

public static string MyMethod<T>(object dataToPassToInterface)
    where T : IMyTypeOfInterface
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

但是,永远不会能够“实例化界面”。

答案 3 :(得分:0)

您无法实例化接口,但可以确保作为generic参数传递的类型实现接口:

    public static string MyMethod<T>(object dataToPassToInterface)
        where T : IMyTypeOfInterface
    {
        // an instance of IMyTypeOfInterface knows how to handle  
        // the data that is passed in 
    }