简体   繁体   中英

How to constrain type of generic extension

I am trying to extend a specific class (say WPF's StackPanel). Let's call this extension MyGenericPanel. I guess its declaration should be:

class MyGenericPanel : StackPanel

But... if I want this extension to hold variable type of reference (say T) declaration would become:

class MyGenericPanel<T> : StackPanel

Now what if I want to restrict T to be of type Identifiable... where Identifiable is another class.

class MyGenericPanel<T> where T: Identifiable, StackPanel

complains that StackPanel should come first... if I put

class MyGenericPanel<T> where T: StackPanel, Identifiable

the compiler complains Identifiable should come before StackPanel.

Bottomline:

  1. MyGenericPanel extends StackPanel
  2. T is an extension of Identifiable
  3. MyGenericPanel has no XAML definition... It is C# code-only.

How can I do this?... (or, can it be done?)

I think you are confusing the specfication of the base class with the generic type constraint:

 class MyGenericPanel<T> : StackPanel where T: Identifiable

The class that comes after MyGenericPanel<T> : is the base class, the class after where T: is the generic type constraint

MyGenericPanel extends StackPanel

T is an extension of Identifiable

translated into

class MyGenericPanel<T> : StackPanel where T : Identifiable

Now what if I want to restrict T to be of type Identifiable... where Identifiable is another class

well if Identifiable and StackPanel are both classes than it can't work because putting 2 class type contraints would mean multiple inheritance , something that's not allowed in C#. That's why the complier complains about your constraints .

If you mean to have your MyGenericPanel<T> extend the functionality of StackPanel and restrict T to be of type Identifiable , then following would work :

class MyGenericPanel<T> : StackPanel where T : Identifiable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM