泛型的一點遺憾

2021-09-05 06:21:31 字數 1479 閱讀 9881

在專案中,我定義了乙個throwhelper輔助類,用於丟擲專案中的自定義異常。例如定義了這樣的乙個異常:

public

class

public employeeexception(

string message)

: base(message)

public employeeexception(

string message, exception innerexception)

: base(message, innerexception)

} 我們可以在throwhelper中定義丟擲該異常的方法,以便於呼叫者呼叫:

public

static

class

throwhelper

public

static employeeexception throwemployeeexception(

string message, exception innerexception)

} public

static

class

throwhelpergeneric

new()

public

static tcustomexception throwcustomexception(

string message, exception innerexception)

} 可惜,泛型型別並不支援帶參的構造函式呼叫。要解決這一問題,只有使用反射技術。實現如下:

public

static

class

throwhelpergeneric

new()

).invoke(

newobject

);throw exception;

}public

static tcustomexception throwcustomexception(

string message, exception innerexception)

).invoke(

newobject

);throw exception;

}} 然而,我總感到非常遺憾,既然泛型的where約束中可以使用new(),那麼,為何不能提供帶參的建構函式約束呢?例如這樣的實現:

public

static

class

throwhelpergeneric

new(),

new(

string),

new(

string, exception)

public

static tcustomexception throwcustomexception(

string message, exception innerexception)

} 不知在將來的c#版本中可否提供這樣的泛型支援呢?莫非,實現這樣的語法還存在相當的難度?

關於java泛型的一點理解

一 boolean addall collection c 泛型,extends 表示乙個邊界限制。如果e是乙個介面,extends表示需要乙個實現了此介面的類來對泛型引數進行指定。如果e是乙個類,則可表示使用其子類,可以認為extends表達了乙個 得關係 static 表示後面會用到 colle...

注入與泛型的一點疑惑

qualifier 會直接注入 commondao 不會是它的 子類 不是子dao,別的地方dao 又沒有用范型,會變成commondao 再加上原有的 會出現兩個commondao,這個時候注入commondao時候發現有兩個,就報錯了。component public class activit...

每天學一點Swift 泛型 一

一 泛型的作用 1.泛型是一種非常靈活的語法,泛型允許程式在函式 列舉 結構體 類中定義型別形參,這種型別形參實際代表的型別是動態改變的 程式可以等到真正使用這些函式 列舉 結構體時才為這些型別形參傳入實際的型別。而且每次使用這些函式 列舉 結構體 類時都可以為泛型的型別形參傳入不同的型別。2.例項...