[英]Write a Generic Method that references static generic collections?
我必须编写一个将参数字符串,int,short,long,float或double用作参数的方法,然后为该参数分配一个随机值,并将其存储在静态ConcurrentDictionary
。 性能是主要限制因素,因此我不想采用会牺牲性能的设计
例:
public void StoreVal<T>(T val)
{
//Check if the val is already in the respective dictionary
//If not, then create a random value
//Store both values in the dictionary
}
我为期望的每种数据类型创建了一个静态ConcurrentDictionary。 我现在面临的关键问题是,如何在通用方法中引用正确的集合类型,而不必使用大量的if / else语句?
更新:我正在使用ConcurrentDictionary,因为此方法将(至少)由8个线程调用,并且我必须确保传递的参数只有一个映射值。 另一个约束是每个数据类型都应具有自己的映射,即如果10(int)-> 25(int),则不需要10(short)指向25(short)-这就是为什么我为单独的ConcurrentDictionary创建了一个原因每个数据类型。
如果性能是至关重要的, 如果组可能的输入类型的限制和已知的,可以考虑使用功能,而不是超载的通用功能:
public void StoreVal(int val) { // no if needed, you know which Dictionary to use }
public void StoreVal(float val) { // no if needed, you know which Dictionary to use }
public void StoreVal(double val) { // no if needed, you know which Dictionary to use }
// etc ...
其他解决方案将需要利用分支,强制转换或某种形式的拳击,这在任何情况下都会降低您的性能。
您可以简单地调用GetOrAdd
来添加值(如果尚不存在):
private ConcurrentDictionary<object, object> dictionary;
public void StoreVal<T>(T val)
{
dictionary.GetOrAdd(val, _ => ComputeRandomValue());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.