简体   繁体   中英

Initialising Generic class with Values

I have a generic class of NameMap() (showing code of interest)

public class NameMap<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    private Dictionary<T2, T1> _backward = new Dictionary<T2, T1>();

    public void addBidirectional(T1 modelName, T2 bussinessName)
    {
        _forward.Add(modelName, bussinessName);
        _backward.Add(bussinessName, modelName);
    }

The nameMap should be initiated with values as it is created eg (Blue,red) for the forward and (red, blue) for the backward dictionary.

I want to have a setup function within this class eg:

    public void setUpBusinessNames()
    {
        this.addBidirectional(("blue", "red");
    }

However, as the class is generic the strings conflict with the generic types.

I've though some ways of solving this:

  1. Passing an instantiated object into setUpBusinessNames of type NameMap<String,String>
  2. Possibly restrict the namemap class to strings?

Anyone got a good way to do this?

You could try this way:

public void setUpBusinessNames()
{
   (this as NameMap<string,string>).addBidirectional("blue", "red");
}

But this object must be an instance of NameMap<string, string> .

make the generic class as abstract and then create another class which inherits it like this :

public abstract class NameMap<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    
    private Dictionary<T2, T1> _backward = new Dictionary<T2, T1>();
    
    public void Add(T1 modelName, T2 bussinessName)
    {
        _forward.Add(modelName, bussinessName);
        _backward.Add(bussinessName, modelName);
    }
    
    public abstract void SetUp();
}

public class NameMapString : NameMap<string, string>
{
    public NameMapString () : base() { }

    public override void SetUp()
    {
        Add("blue", "red");
    }
}

this would enforce the type. If you need another type, just create another class and do the same procedure.

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