[英]Generic type constraint does not enable assignment without explicit cast
我不敢相信我多年的 C# 經驗花了我這么長時間才發現以下限制,我也不敢相信這是不可避免的,如果有人能相反地啟發我,我會非常高興。 考慮以下:
namespace ConsoleApp1;
internal class BaseClass { }
internal class DerivedClass : BaseClass { }
internal class CastingExperiment
{
public void AssignmentAttempts<TBase>(object anyRandomThing)
where TBase : BaseClass
{
BaseClass baseClass = new DerivedClass();
TBase wantToDoThis = new BaseClass(); // Compiler says no, cannot implicitly convert type
TBase haveToDoThis = (TBase)baseClass;
TBase whichIsAsEvilAsThis = (TBase)anyRandomThing;
}
}
在這種情況下,我會盡快避免顯式轉換,類型約束就在那里告訴編譯器它需要知道什么關於賦值兼容性,但仍然需要轉換。
我也嘗試過從接口派生CastingExperiment
並使用 TBase 的協變或逆變約束,它仍然堅持TBase
。 我錯過了什么嗎?
where TBase : BaseClass
的約束意味着TBase
可以是任何類型的IS BaseClass
- 它可以是BaseClass
或任何派生自它的類型。
當您使用new BaseClass();
您應該有相同類型的引用( BaseClass
),但您的引用類型是TBase
(可以是任何派生類型)。
所以當你這樣調用你的方法時:
someInstance.AssignmentAttempts<DerivedClass>(someArg);
那么非工作行將導致如下結果:
DerivedClass wantToDoThis = new BaseClass(); // check the reference type
如果您只是以這種方式編寫代碼(沒有泛型),您將收到編譯時錯誤。
您可以將派生類型轉換為基本類型,但反之則不行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.