3 回答

TA貢獻1825條經(jīng)驗 獲得超6個贊
約束不是簽名的一部分,但參數(shù)是簽名的一部分。在重載解析過程中會強制執(zhí)行參數(shù)約束。
因此,讓我們將約束放入?yún)?shù)中。很難看,但是可以用。
class RequireStruct<T> where T : struct { }
class RequireClass<T> where T : class { }
static void Foo<T>(T a, RequireStruct<T> ignore = null) where T : struct { } // 1
static void Foo<T>(T? a) where T : struct { } // 2
static void Foo<T>(T a, RequireClass<T> ignore = null) where T : class { } // 3
(遲到比沒有遲到六年嗎?)

TA貢獻1859條經(jīng)驗 獲得超6個贊
在第一種方法上刪除結(jié)構(gòu)約束。如果需要區(qū)分值類型和類,則可以使用參數(shù)的類型來實現(xiàn)。
static void Foo( T? a ) where T : struct
{
// nullable stuff here
}
static void Foo( T a )
{
if( a is ValueType )
{
// ValueType stuff here
}
else
{
// class stuff
}
}
- 3 回答
- 0 關(guān)注
- 647 瀏覽
添加回答
舉報