Getting rid of redundant type parameters

I have a generic class A and another class B that processes instances of A and contains some additional data. I need to have two separate classes. B cannot inherit from A, since A has other derivatives, B must contain a reference to A.

As a simple example, I would like to write this (the dictionary is A, dicthandler - B):

class dicthandler<T> where T : Dictionary<Tk, Tv>

But it does not compile, I need to specify all parameters of the type:

class dicthandler<T, Tk, Tv> where T : Dictionary<Tk, Tv>

But I really don’t care what Tk and Tv are, so they are completely redundant, I just need T. Whenever I want to create a new instance, I need to specify all the type parameters for the constructor, which is harmful to me.

So clear, I need some tricks. Any ideas?

+3
source share
3 answers

, . DictHandler T, TKey TValue.

, , , , . :

public static class DictHandler
{
    public static DictHandler<T, TKey, TValue> CreateHandler<T, TKey, TValue>
        (T dictionary1, Dictionary<TKey, TValue> dictionary2)
        where T : Dictionary<TKey, TValue>
    {
        return new DictHandler<T, TKey, TValue>();
    }
}

public class DictHandler<T, TKey, TValue> where T : Dictionary<TKey, TValue>
{
}

:

Dictionary<string, int> dict = new Dictionary<string, int>();
var handler = DictHandler.CreateHandler(dict, dict);

, , , , ( ) , . , , , , .

A, . , ( , ), :

public interface INonGenericDictionary
{
    // Members which don't rely on the type parameters
}

public class Dictionary<TKey, TValue> : INonGenericDictionary
{
    ...
}

public class DictHandler<T> where T : INonGenericDictionary
{
    ...
}

, , .

+5

, # , . , , CreateDictHandler -:

private dicthandler<T, Tk, Tv> CreateDictHandler() {...}
...
var handler = CreateDictHandler();

, var .


, . , , , IDictionary ( ), .

+2

, . , ?

class dicthandler<TKey, TValue>

Then you can just use a type Dictionary<TKey, TValue>. Obviously, your type will only be used with dictionaries, so there should be no need to force this type to be passed as a general argument, since you already know what it is.

+1
source

Source: https://habr.com/ru/post/1783186/


All Articles