. NET supports type parameter constraints in the following five ways:
where T:struct | T must be a struct type
where T:class | T must be a class type
where T:new () | T must have an argument-free constructor
where T:nameofbaseclass | T must inherit a class named Nameofbaseclass
where T:nameofinterface | T must implement an interface named Nameofinterface
The parent form of the current form (or user control) is obtained in WPF as follows, and the qualified generic must be class:
Private voidBtncancel_click (Objectsender, RoutedEventArgs e) {Window Hostwindow= getparent<window> (Sender asButton); if(Hostwindow! =NULL) {hostwindow.close (); } } Public StaticT getparent<t> (UIElement UIElement)whereT:class{T result; varDP =logicaltreehelper.getparent (uiElement); Result= DP asT; while(Result = =NULL) {DP=Logicaltreehelper.getparent (DP); Result= DP asT; if(DP = =NULL)return NULL; } returnresult; }
About generic type parameter constraints in C # (where T:class)