2010-03-26 56 views
0

是否有可能创建一个通用的方法与像我可以创建一种类型接口的通用方法吗?

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

我将不得不创建(T)Activator.CreateInstance();接口签名?

回答

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); 
2

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

1

可以约束的类型参数是什么,实现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 
} 

但是,您将永远能够“实例化界面”。

0

你不能实例化接口,但可以确保作为通用参数传递的类型实现接口:

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