C 泛型方法Where 約束

2021-08-14 19:03:41 字數 1885 閱讀 5639

where(泛型型別約束)

定義:在定義泛型的時候,我們可以使用where限制引數的範圍。

使用:在使用泛型的時候,你必須尊守where限制引數的範圍,否則編譯不會通過。

六種型別的約束:

t:類(型別引數必須是引用型別;這一點也適用於任何類、介面、委託或陣列型別。)

class myclasswhere t : class

///約束t引數必須為「引用 型別」

where u : struct

///約束u引數必須為「值 型別」

t:結構(型別引數必須是值型別。可以指定除 nullable 以外的任何值型別。)

class myclasswhere t : class

///約束t引數必須為「引用 型別」

where u : struct

///約束u引數必須為「值 型別」

t:new()(型別引數必須具有無引數的公共建構函式。當與其他約束一起使用時,new() 約束必須最後指定。)

class employeelistwhere t : employee, iemployee, system.icomparable, new

()

t:《基類名》(型別引數必須是指定的基類或派生自指定的基類。)

public

class

employee{}

public

class genericlistwhere t : employee

t:《介面名稱》(型別引數必須是指定的介面或實現指定的介面。可以指定多個介面約束。約束介面也可以是泛型的。)

///

///介面

/// inte***ce

imyinte***ce

//////

定義的乙個字典型別

/// ///

///class dictionarywhere

tkey : icomparable, ienumerable

where

tval : imyinte***ce

}

t:u(為 t 提供的型別引數必須是為 u 提供的引數或派生自為 u 提供的引數。也就是說t和u的引數必須一樣

class list

}

一、可用於類:

public

class mygenericclasswhere t:icomparable

二、可用於方法:

public

bool mymethod(t t) where t : imyinte***ce

三、可用於委託:

delegate t mydelegate() where t : new()
在實際專案中什麼時候用到它們?

有時候你在做乙個專案的時候,你需要用到泛型,你只希望傳給你的泛型引數是限定範圍的,

比如你希望值型別,或者是引用型別,或者是繼承至某個型別、或者是符合某個接扣的型別,

這個時候你該如何辦?你就需要用到 where 來限定了。

**:

C 泛型 WHERE 約束

where 子句用於指定對下列型別的約束 這些型別可用作泛型宣告中定義的型別形參的實參。public class mygenericclass t wheret icomparable t實現icomparable介面 public void request listentitylist where...

where泛型約束

where用於指定型別約束,這些約束可以作為泛型宣告中定義的型別引數的變數.如下 public class mygenericclasswhere t icomparable 除了介面約束,where還可以包括基類約束,以指出某個型別必須將指定的類作為基類 或者就是該類本身 才能用作該泛型的型別引數...

where(泛型型別約束)

定義 在定義泛型的時候,我們可以使用 where 限制引數的範圍。使用 在使用泛型的時候,你必須尊守 where 限制引數的範圍,否則編譯不會通過。net支援的型別引數約束 where t struct t必須是乙個結構型別 where t class t必須是乙個class型別 where t n...