如何将对象强制转换为泛型字典



通用字典如下:

public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>

具体词典可以如下:

var container = new ConcurrentDictionary<string, Unit>();
var container = new ConcurrentDictionary<string, CustomUnitClass>();

这些特殊字典(具有不同的参数)已添加到应用程序状态中:

HttpContext.Current.Application[key] = container;

当我从应用程序状态获取项目时(这里的一些人帮助了我;谢谢他们),我能够以这种方式检查类型是否为ConcurrentDictionary:

object d = HttpContext.Current.Application[i];
if (d.GetType().GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>))

最后一点是 - 如何将对象 d 转换为通用 ConcurrentDictionary:

ConcurrentDictionary<?, ?> unit = d as ConcurrentDictionary<?, ?>;

我不想使用特定的演员阵容,如下所示:

ConcurrentDictionary<string, Unit> unit = d as ConcurrentDictionary<string, Unit>;

因为第二个参数可以是另一种类型。

提前谢谢你。

我想你可能以一种稍微错误的方式看待泛型,但没关系,让我们谈谈!

你的IDictionary<TKey, TValue>是完美的,你正确地使用它,但是我认为在回铸时,除非你明确知道你期望的类型是什么,否则投射它没有真正的意义。

或者我会推荐什么,为了强烈的可爱; 你提到潜在的第二种类型,也就是TValue会有所不同......这是使用界面的最佳时机!让我演示一下。

我们的界面

public interface IModeOfTransport
{
    string Name { get; set; }
    string Colour { get; set; }
    bool CanFloat { get; set; }
    bool CanFly { get; set; }
    int NumberOfPassengers { get; set; }
}

我们的对象

public class Car : IModeOfTransport
{
    // ...
}
public class Plane : IModeOfTransport
{
    // ...
}
public class Boat : IModeOfTransport
{
    // ...
}

我们的实施

var modesOfTransport = new Dictionary<string, IModeOfTransport>();
modesOfTransport.Add("First", new Car());
modesOfTransport.Add("First", new Plane());
modesOfTransport.Add("First", new Boat());

让我们休息一下

从上面可以看出,我们有一个字典,其键类型为 string 和值类型 IModeOfTransport .这允许我们对IModeOfTransport接口的所有属性和方法进行显式强类型访问。如果需要访问字典中泛型值的特定信息,并且不知道实际的对象类型转换是什么,则建议这样做。通过使用接口,它使我们能够找到相似之处。

快完成了

object dictionary = HttpContext.Current.Application[i];
if (dictionary.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    var modesOfTransport = dictionary as Dictionary<string, IModeOfTransport>;
    foreach (var keyValuePair in modesOfTransport)
    {
        // ...
    }
}

最新更新