无法从'System.Type'转换为我自己定义的界面

时间:2013-07-22 04:25:47

标签: c# generics types constraints typeconverter

我定义了自己的IExportable界面,并将其用作

public static A SomeAction<B>(IList<T> data) where T : IExportable
{
    var tType = typeof(T);
    IList<B> BLists = SomeMethod(tType);
    //...
} 

SomeMethod是:

List<B> SomeMethod(IExportable exportData)
{
   // do somethings
}

但是当我运行我的应用程序时出现此错误:

SomeMethod(IExportable)的最佳重载方法匹配包含一些无效参数 无法从'System.Type'转换为'IFileExport'
我的错在哪里?

1 个答案:

答案 0 :(得分:1)

typeof(T)返回一个Type对象,该对象包含有关由T表示的类的元信息。 SomeMethod正在寻找扩展IExportable的对象,因此您可能希望创建一个扩展T的{​​{1}}对象。您有几个选项可以做到这一点。最直接的选项可能是在您的通用参数上添加IExportable约束并使用new的默认构造函数。

T

我已明确说明了//Notice that I've added the generic paramters A and T. It looks like you may //have missed adding those parameters or you have specified too many types. public static A SomeAction<A, B, T>(IList<T> data) where T : IExportable, new() { T tType = new T(); IList<B> BLists = SomeMethod(tType); //... } 的类型,以便更好地说明代码中发生了什么:

tType
相关问题