簡體   English   中英

正確使用 <T> 在C#中輸入通用方法

[英]Properly using of the <T> type in generic methods in C#

因此,我的實際方法有很多不同,但我會得出結論。 在使用通用方法時,我似乎不太了解如何處理通用<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

所以我錯了。 難道不是可以做到這一點的想法-在編譯時聲明一個通用類型並在運行時轉換為更特定的類型嗎?

你不能那樣做。 檢查以下情況:

您還有一個名為SomeMoreSpecificEntity2類,該類已聲明:

class SomeMoreSpecificEntity2 : Entity
{
}

您調用方法ChangeCode<SomeMoreSpecificEntity2> ,因此TSomeMoreSpecificEntity2 ,因此tempEntitySomeMoreSpecificEntity2 ,但是您正在嘗試為其分配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而並非出於無法運行T的目的,因此可以更改當前代碼以使其成為非通用方法,只需將tempEntity聲明為Entity類型。 當然,這可能對您真正想做的事情不起作用,但是由於您只提供了不起作用的代碼,因此很難確定:(

關於這條線的三點:

if (entity.GetType() == typeof(SomeMoreSpecificEntity))
  • 您實際上是說entityT類型而不是Entity類型嗎? 目前可以是任何實體
  • 您真的要檢查確切的類型嗎? 通常你會使用is ,而不是調用GetType ,並直接與類型比較它
  • 通常比較這種類型的跡象表明您應該考慮重新設計。 在這一點上,它絕對不是通用的 ,因為它只能處理其中經過硬編碼的類型。
tempEntity = (T)(object)new SomeMoreSpecificEntity();

T只能與物體一起施放

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM