简体   繁体   中英

C# Generics: Defining only one type as generic

I have a class which will wrap a dictionary to perform some operations on it. I am trying to instantiate it like:

class DescriptorList<K, Descriptor>
{
     <some code>
}

Descriptor is a class that I implemented but for some reason the compiler doesnt recognize that and thinks its a generic keyword (like 'T'). How do I make the compiler recognize my type.

If you only want the key to be generic in your wrapping type, you don't need a type descriptor in your class declaration for the value. You only need to specify the value type (Descriptor) when you're declaring the Dictionary instance you're wrapping. For example:

class DescriptorList<K>
{
   private Dictionary<K, Descriptor> wrapped = new Dictionary<K, Descriptor>() ;

   ...
}

You can implement your class like this, if you want to have dictionary with fixed type for values and vary type for keys.

class Descriptor
{}

class DescriptorList<K> : Dictionary<K, Descriptor>
{
     <some code>
}

or you can use this, if you want to have dictionary with fixed type for keys and vary type for values.

class Descriptor
{}

class DescriptorList<K> : Dictionary<Descriptor, K>
{
     <some code>
}

will wrap a dictionary

class DescriptorList<K>
{
   private readonly Dictionary<K, Descriptor> wrappedDictionary;

   //   <some code>
}

What you are trying to do is not possible with your current implementation. You may do the following (although it is just a workaround and depends on what you are trying to achive);

public class DescriptorList<K, V> where V : Descriptor
{        
}

Syntactically, Descriptor here is just a generic parameter, like T . If you don't want it to be part of the generic, just use:

class DescriptiorList<K> { ... }

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