无法强制类型为'MyType'输入'IMyInterface ' 1[System.IConve

本文关键字:IMyInterface System IConve 输入 MyType 类型 | 更新日期: 2023-09-27 18:12:53

我在将实现类转换为泛型接口时遇到了一个问题。我在一个类中有几个内部类来实现这个接口。然后我有一个方法,它应该返回这些类中的任何一个,但是它包含的强制转换失败了,对于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);
}

看到字符串是引用类型,而其他是结构体,这是相关的吗?我肯定漏掉了什么。(可能也相关:如果我删除T的协方差,强制转换MyStringClass也会失败。)

我通常不使用c#,所以这对我来说有点陌生。任何解释为什么这个不能工作,以及任何指向解决方案的指针都是受欢迎的。

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

EDIT2:正如Alireza在后面的回答中解释的那样,使T协变使它不支持值,类型,这解释了为什么T = String有效,而T = ValueType无效。

无法强制类型为'MyType'输入'IMyInterface ' 1[System.IConve

您放在T前面的out修饰符使其协变,但来自MSDN文档的out:

引用类型支持协方差和逆变,值类型不支持协方差和逆变。

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

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