Generics 如何将对象强制转换到通用字典?

Generics 如何将对象强制转换到通用字典?,generics,dictionary,Generics,Dictionary,通用词典如下: public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue> var container = new ConcurrentDictionary<string, Unit>(); var container = new ConcurrentDictionary<string, CustomUnitClass>(); ConcurrentDic

通用词典如下:

public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>
var container = new ConcurrentDictionary<string, Unit>();
var container = new ConcurrentDictionary<string, CustomUnitClass>();
ConcurrentDictionary<string, Unit> unit = d as ConcurrentDictionary<string, Unit>;
当我从应用程序状态获取项目时(这里的一些人帮助了我,谢谢他们),我可以通过以下方式检查类型是否为ConcurrentDictionary:

object d = HttpContext.Current.Application[i];
if (d.GetType().GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>))
objectd=HttpContext.Current.Application[i];
if(d.GetType().GetGenericTypeDefinition()==typeof(ConcurrentDictionary))
最后一点是——如何将对象d强制转换为通用ConcurrentDictionary:

ConcurrentDictionary<?, ?> unit = d as ConcurrentDictionary<?, ?>;
ConcurrentDictionary单元=d作为ConcurrentDictionary;
我不想使用特定的强制转换,如下所示:

public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>
var container = new ConcurrentDictionary<string, Unit>();
var container = new ConcurrentDictionary<string, CustomUnitClass>();
ConcurrentDictionary<string, Unit> unit = d as ConcurrentDictionary<string, Unit>;
ConcurrentDictionary单元=d作为ConcurrentDictionary;
因为第二个参数可以是另一种类型

提前谢谢你。

我想你对泛型的理解可能有点错误,但没关系,让我们谈谈吧

您的
IDictionary
非常完美,您正确地使用了它,但是我认为,当涉及到回溯时,除非您明确知道您期望的类型,否则回溯没有真正的意义

或者我会推荐什么,为了强类型的可爱;您提到第二种类型,即
TValue
可能会有所不同。。。这是使用界面的最佳时机!让我示范一下

我们的界面 我们的目标 我们的实施
非常感谢你。这几乎就是我想要的。但问题是,汽车、飞机和船没有什么共同之处。在这种情况下,如何设计IModeOfTransport接口?如果我试图创建一个空的IModeOfTransport接口作为一个标记,那么当我想要获取一些数据时,什么都不会出现。哦,deer,没关系,让我们考虑一下。您试图从字典中的对象中获取哪些信息?你是想得到像名字这样的简单信息,还是更复杂的信息?我们需要的信息正是你所说的,简单的字符串,比如名字。。。但是,它们有稍微不同的属性名称,如Name、UnitName等。顺便说一句,这不是我的设计。我刚开始在一家公司工作,应该根据当前状态做些事情。字典中可以作为第二个参数的类型数量不是太多,我可以检查每种类型,这不是一个聪明的解决方案,但如果没有什么我不能做的,我可以做——暴力法。我同情你的立场。我想推荐的是;虽然这些对象在属性名称上没有直接共享相似性,但它们也会创建一个接口并“强制”它们。我不是建议重新调整逻辑,而是如果接口有一个名为
Name
的属性,但对象属性名为
LongWindedName
,则让对象实现返回
LongWindedName
Name
var modesOfTransport = new Dictionary<string, IModeOfTransport>();
modesOfTransport.Add("First", new Car());
modesOfTransport.Add("First", new Plane());
modesOfTransport.Add("First", new Boat());
object dictionary = HttpContext.Current.Application[i];
if (dictionary.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    var modesOfTransport = dictionary as Dictionary<string, IModeOfTransport>;
    foreach (var keyValuePair in modesOfTransport)
    {
        // ...
    }
}