【问题标题】:Cannot convert from 'System.Type' to myself defined interface无法从“System.Type”转换为自己定义的接口
【发布时间】:2013-07-22 04:25:47
【问题描述】:

我定义了自己的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) 返回 System.Type 的实例,但您的方法采用 IExportable。

标签: c# generics types constraints typeconverter


【解决方案1】:

typeof(T) 返回一个Type 对象,该对象具有关于由T 表示的类的元信息。 SomeMethod 正在寻找一个扩展 IExportable 的对象,因此您可能想要创建一个扩展 IExportableT 对象。你有几个选项可以做到这一点。最直接的选择可能是在泛型参数上添加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);
    //...
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多