第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

C#
冉冉說 2019-10-31 14:10:30
我想?yún)^(qū)分以下幾種情況:普通值類型(例如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'已經(jīng)定義了具有相同參數(shù)類型的成員'Foo'。好吧,我無法以where T : struct和區(qū)別where T : class。如果刪除第三個函數(shù)(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)進行編譯,將其映射到上述函數(shù)之一(或第三個具有另一個約束的函數(shù),我沒有想到)?
查看完整描述

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

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


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

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

         }

      }


查看完整回答
反對 回復(fù) 2019-10-31
  • 3 回答
  • 0 關(guān)注
  • 647 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號