[英]Initialising Generic class with Values
I have a generic class of NameMap() (showing code of interest)我有一个 NameMap() 的通用类(显示感兴趣的代码)
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. nameMap 应该在创建时使用值启动,例如 (Blue,red) 用于前向字典和 (red, blue) 用于后向字典。
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:我虽然有一些解决这个问题的方法:
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>
.但是这个对象必须是
NameMap<string, string>
一个实例。
make the generic class as abstract
and then create another class which inherits it like this :将泛型类设为
abstract
类,然后创建另一个继承它的类,如下所示:
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.
如果您需要另一种类型,只需创建另一个类并执行相同的过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.