0

所以我的真正方法有很大不同,但我归结为这一点。<T>当我使用泛型方法时,我似乎并不完全理解如何处理泛型类型。我的理解是,当我们希望相同的逻辑适用于不同的类型时,我们使用泛型方法,但我们希望在运行时自由地确定确切的类型。所以对我来说,当我有这样的方法时,这似乎很自然:

internal static void ChangeCode<T>(Entity entity) where T : Entity
{

    T tempEntity;

    if (entity.GetType() == typeof(SomeMoreSpecificEntity))
    {
      tempEntity = new SomeMoreSpecificEntity();
    }
}

但是,如果我尝试这样的事情,我会得到一个错误Can not convert type T to SomeMoreSpecificEntity

所以我错在哪里。能够做到这一点的想法不就是 - 在编译时声明一个通用类型并在运行时转换为更具体的类型吗?

4

3 回答 3

4

你不能那样做。检查以下情况:

你有另一个名为的类SomeMoreSpecificEntity2被声明:

class SomeMoreSpecificEntity2 : Entity
{
}

你调用你的方法ChangeCode<SomeMoreSpecificEntity2>,所以TSomeMoreSpecificEntity2,所以tempEntity也是SomeMoreSpecificEntity2,但你试图分配SomeMoreSpecificEntity给它。那是行不通的。

您可以尝试将其更改为:

internal static void ChangeCode<T>(Entity entity) where T : Entity
{
    Entity tempEntity;

    if (entity.GetType() == typeof(SomeMoreSpecificEntity))
    {
        tempEntity = new SomeMoreSpecificEntity();
    }
}

它编译。

于 2013-03-26T10:40:49.103 回答
3

不,您尝试编写的代码已损坏。例如,假设我打电话给:

ChangeCode<BananaEntity>(new SomeMoreSpecificEntity());

这将尝试将类型的引用分配给类型SomeMoreSpecificEntity的变量T,其中Tis BananaEntity

目前尚不清楚您要实现什么,但这就是您当前的代码无法编译的原因。鉴于您实际上并没有 T其他用途用于它不起作用的目的,因此可以更改当前代码以使其成为非泛型方法,并仅声明tempEntity为 type Entity。当然,这可能不适用于您真正想做的事情,但是由于您只提供了非工作代码,因此很难确定:(

关于这条线的三点:

if (entity.GetType() == typeof(SomeMoreSpecificEntity))
  • 你真的是entity想成为 typeT而不是 typeEntity吗?目前它可以是任何实体
  • 你真的想检查确切的类型吗?通常你会使用is而不是直接调用GetType它并将其与类型进行比较
  • 通常比较像这样的类型表明您应该考虑重新设计。在这一点上它绝对不是通用的,因为它只处理其中硬编码的类型。
于 2013-03-26T10:40:06.883 回答
-3
tempEntity = (T)(object)new SomeMoreSpecificEntity();

T 只能与对象一起投射

于 2013-03-26T10:44:43.793 回答