[英]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>
,因此T
為SomeMoreSpecificEntity2
,因此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
的變量,其中T
是BananaEntity
。
目前尚不清楚您要實現的目標,但這就是為什么您當前的代碼無法編譯的原因。 鑒於您實際上並未使用 T
而並非出於無法運行T
的目的,因此可以更改當前代碼以使其成為非通用方法,只需將tempEntity
聲明為Entity
類型。 當然,這可能對您真正想做的事情不起作用,但是由於您只提供了不起作用的代碼,因此很難確定:(
關於這條線的三點:
if (entity.GetType() == typeof(SomeMoreSpecificEntity))
entity
是T
類型而不是Entity
類型嗎? 目前可以是任何實體 is
,而不是調用GetType
,並直接與類型比較它 tempEntity = (T)(object)new SomeMoreSpecificEntity();
T只能與物體一起施放
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.