亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通用約束,其中T:struct和T:class

通用約束,其中T:struct和T:class

C#
冉冉說 2019-10-31 14:10:30
我想區分以下幾種情況:普通值類型(例如int)可為空的值類型(例如int?)引用類型(例如string)-可選,我不在乎是否將其映射到上面的(1)或(2)我想出了以下代碼,在情況(1)和(2)下工作正常:static void Foo<T>(T a) where T : struct { } // 1static void Foo<T>(T? a) where T : struct { } // 2但是,如果我嘗試檢測這種情況(3),它將無法編譯:static void Foo<T>(T a) where T : class { } // 3錯誤消息是類型'X'已經定義了具有相同參數類型的成員'Foo'。好吧,我無法以where T : struct和區別where T : class。如果刪除第三個函數(3),則以下代碼也不會編譯:int x = 1;int? y = 2;string z = "a";Foo (x); // OK, calls (1)Foo (y); // OK, calls (2)Foo (z); // error: the type 'string' must be a non-nullable value type ...如何Foo(z)進行編譯,將其映射到上述函數之一(或第三個具有另一個約束的函數,我沒有想到)?
查看完整描述

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

(遲到比沒有遲到六年嗎?)


查看完整回答
反對 回復 2019-10-31
?
BIG陽

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

         }

      }


查看完整回答
反對 回復 2019-10-31
  • 3 回答
  • 0 關注
  • 649 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號