2

你能帮我理解这种情况下的错误吗?

public interface IGeneralInterface
{
}


public class A : IGeneralInterface
{
}

public class B : IGeneralInterface
{
}

public class SomeClass<TGenericType> where TGenericType : IGeneralInterface
{
    private TGenericType internalValue;

    public SomeClass(TGenericType InitValue)
    {
        internalValue = InitValue;
    }

    public TGenericType CreateAnother()
    {
       TGenericType val1 = new B();   //Error here: class B() could not be converted to TGenericType
       return val1;
    }
}

即使我建立SomeClass<T>as

SomeClass<IGeneralInterface> someClass = new SomeClass<IGeneralInterface>();

我明确传递基本接口以包含所有(?)案例,​​但它仍然抛出错误

4

3 回答 3

3

改变

 TGenericType val1 = new B();   //Error here: class B() could not be converted to TGenericType

  IGeneralInterface val1 = new B();   

您正在尝试 TypeCast IGeneralInterfaceTGenericType这是导致错误的原因。

TGenericType可能有其他约束,比如它继承自ISpecificInterfaceB继承。在这种情况下,分配变得无效。

例子:

public class SomeClass< TGenericType> where TGenericType : IGeneralInterface, ISpecificInterface
TGenericType val1 = new B(); // TGenericType should be ISpecificInterface also, B is not.

上面运行。IGenericInterface应该总是比TGenericType.

 public class SomeClass <IGenericInterface> 

或者,您可以使用is关键字来确定对象是否可分配TGenericType,然后使用强制转换。

TGenericType val1 = default(TGenericType);
var val = new B();
if ( val is TGenericType)
{
  val1 = (TGenericType)val;
}

编辑对于以下评论

它如何在运行时有额外的要求?我在此处列出的编译器中的所有内容

CreateAnother()B创建非通用类型的实例。以下面的例子

SomeClass<C> c = new SomeClass<C();
C another = c.CreateAnother(); // C is not assignable from B. (C is below). But It would be valid, if compiler did not flag the error

public class C : IGeneralInterface, IDisposable
{
}
于 2013-01-01T12:22:26.037 回答
1

为什么您认为 anew B()应该可转换为TGenericType?唯一知道的TGenericType是它实现了接口。

例如,new B()不能转换为 type A

我不知道您要获得什么,但您可以将通用约束更改为:

public class SomeClass<TGenericType>
    where TGenericType : class, IGeneralInterface, new()

然后可以new TGenericType()在您的 create 方法中说。

但是不再可能使用该类型SomeClass<IGeneralInterface>,因为该接口没有可访问的无参数实例构造函数(当然,没有接口可以具有构造函数)。

于 2013-01-01T12:33:51.803 回答
0

您的代码中的问题是您正在声明变量

val1 

类型的

TGenericType

然后你尝试用不同类型的对象实例化它。

即使您已经声明了类的泛型类型必须在继承层次结构中的条件,IGeneralInterface它们对于编译器也是不同的。我假设在此设置中您必须使用显式强制转换。

于 2013-01-01T12:29:48.260 回答