无法从';转换;System.Type';到我自己定义的接口
本文关键字:我自己 定义 接口 转换 System Type | 更新日期: 2023-09-27 18:24:22
我定义了自己的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"
我的错在哪里?
typeof(T)
返回一个Type对象,该对象包含有关T
表示的类的元信息。SomeMethod
正在寻找一个扩展IExportable
的对象,因此您可能希望创建一个扩展了IExportable
的T
对象。你有几个选择。最直接的选择可能是在泛型参数上添加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
的类型,以更好地说明代码中发生了什么:
public static A SomeAction<B>(IList<T> data) where T : IExportable
{
//Notice what typeof returns.
System.Type tType = typeof(T);
IList<B> BLists = SomeMethod(tType);
//...
}