3 回答

TA貢獻1825條經驗 獲得超6個贊
約束不是簽名的一部分,但參數是簽名的一部分。在重載解析過程中會強制執行參數約束。
因此,讓我們將約束放入參數中。很難看,但是可以用。
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條經驗 獲得超6個贊
在第一種方法上刪除結構約束。如果需要區分值類型和類,則可以使用參數的類型來實現。
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 關注
- 649 瀏覽
添加回答
舉報