c# - 无法将类型为 'MyType' 的对象转换为类型 'IMyInterface` 1[System.IConvertible]'

标签 c#

我在将实现类转换为通用接口(interface)时遇到问题。 我在一个实现此接口(interface)的类中有几个内部类。 然后我有一个方法应该返回这些类中的任何一个,但它包含的转换对于 T != String 失败。

示例:

public interface IMyInterface<out T> where T : IConvertible
{/*Contents*/}

internal class MyStringClass : IMyInterface<String>  {/*Contents*/}
internal class MySingleClass : IMyInterface<Single>  {/*Contents*/}

IMyInterface<IConvertible> CreateMyObject(Type type)
{
    return (IMyInterface<IConvertible>)Activator.CreateInstance(type);
}

看String是引用类型,其他都是结构体,有关系吗?这里一定有我想念的东西。 (也可能相关:如果我删除 T 的协方差,转换 MyStringClass 也会失败。)

我通常不使用 C#,所以这对我来说有点陌生。欢迎任何关于为什么这不起作用的解释,以及任何指向解决方案的指示。

编辑:我实现 IMyInterface 的内部类作为 type (typeof)

传递

EDIT2:正如 Alireza 在下面的答案中解释的那样,使 T 协变使其不支持值和类型,这解释了为什么 T = String 有效,但 T = ValueType。不过,我仍然对如何完成这项工作感到困惑...

最佳答案

放在 T 前面的 out 修饰符使它成为协变的,但是来自 MSDN document for out :

Covariance and contravariance are supported for reference types, but they are not supported for value types.

更新:有时(如果您的设计允许并且您不需要类外的非泛型东西)您可以使用非泛型接口(interface)来解决问题:

public interface IMyInterface
{ /*non-generic content*/}

public interface IMyInterface<out T> : IMyInterface where T : IConvertible
{/*Contents*/}

internal class MyStringClass : IMyInterface<String> {/*Contents*/}
internal class MySingleClass : IMyInterface<Single> {/*Contents*/}

static IMyInterface CreateMyObject(Type type)
{
    return (IMyInterface)Activator.CreateInstance(type);
}

关于c# - 无法将类型为 'MyType' 的对象转换为类型 'IMyInterface` 1[System.IConvertible]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754695/

相关文章:

c# - 如何在 WP8 ListBox 中使用水平方向?

c# - 如何确定异常的基类是否为 OperationCanceledException?

c# - 使用 Xamarin 实现新的 Google 登录

C# 实现过程 block

c# - 哈希表的通用版本是什么?

c# - 单选按钮检查验证

c# - 许多条目带有 OnItemsChanged(),如何删除旧条目

c# - Lambda 或 Linq 方法来搜索多个参数

c# - 自定义标签不显示文本字符串

javascript - 从 ASP.NET 代码后面的 javascript 警报中获取 ok