正确使用<;T>;在C#中的泛型方法中键入

本文关键字:泛型方法 lt gt | 更新日期: 2023-09-27 18:06:06

所以我真正的方法有很多不同,但我归结为这一点。当我使用泛型方法时,我似乎不完全理解如何处理泛型<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

那么我错在哪里了。难道不能做到这一点吗?在编译时声明一个公共类型,并在运行时强制转换为更具体的类型?

正确使用<;T>;在C#中的泛型方法中键入

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

您有另一个名为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();
    }
}

它编译。

不,您试图编写的代码已损坏。例如,假设我调用了:

ChangeCode<BananaEntity>(new SomeMoreSpecificEntity());

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

目前还不清楚您想要实现什么,但这就是当前代码无法编译的原因。假设您实际上并不是在使用T,而不是出于它不起作用的目的,则可以更改当前代码,使其成为非泛型方法,并将tempEntity声明为类型Entity。当然,这可能不适用于你真正想做的事情,但由于你只提供了不起作用的代码,这很难确定:(

关于这条线的三点:

if (entity.GetType() == typeof(SomeMoreSpecificEntity))
  • 你的意思是entityT型而不是Entity型吗?目前,它可以是任何实体
  • 你真的想检查确切的类型吗?通常您会使用is,而不是调用GetType并直接将其与类型进行比较
  • 通常,比较这样的类型是一个迹象,表明你应该考虑重新设计。在这一点上,它绝对不是泛型,因为它只处理其中硬编码的类型
tempEntity = (T)(object)new SomeMoreSpecificEntity();

T只能使用对象进行强制转换