繁体   English   中英

我可以在C#中将通用类型转换为Dictionary <,>吗?

[英]Can I cast generic type to Dictionary<,> in C#?

我在某些词典集合中有程序设置。
而且我需要通过配置文件( dst字典)中的设置来更新默认设置( src字典)。
因此,我写了一个通用的扩展方法,该方法不适用于字典中的字典:

public static class DictionaryExtensions
{
    public static void Update<T, U>(this Dictionary<T, U> src, Dictionary<T, U> dst)
    {
        // Update values by keys
        var keys = src.Select(x => x.Key).ToArray();
        foreach (var key in keys)
            if (dst.ContainsKey(key))
            {
                if (typeof(U).GetGenericTypeDefinition() == typeof(Dictionary<,>))
                {                                                    // Error in recursively calling:
                    var d1 = src[key] as Dictionary<object, object>; // d1 is null, but it is Dictionary<,>
                    var d2 = dst[key] as Dictionary<object, object>; // d2 is null, but it is Dictionary<,>
                    d1.Update(d2);                                   // How can I call it?
                }
                else
                    src[key] = dst[key];
            }

        // Append not exist values
        keys = dst.Select(x => x.Key).ToArray();
        foreach (var key in keys)
            if (!src.ContainsKey(key))
                src.Add(key, dst[key]);
    }
}

我可以将类U转换为Dictionary <,>的未知类型,然后递归调用Update()方法吗?

使用IDictionay,不使用通用类型,可能可以做到,我还没有尝试过

public static class DictionaryExtensions
{
    public static void Update(this IDictionary src, IDictionary dst)
    {
        foreach (object srcKey in src.Keys)
        {
            foreach (object dstKey in dst.Keys)
            {
                if (dst.Contains(srcKey))
                {
                    IDictionary d1 = src[srcKey] as IDictionary;
                    IDictionary d2 = dst[srcKey] as IDictionary;
                    if (d1 != null && d2 != null)
                    {
                        d1.Update(d2);
                    }
                    else
                        src[srcKey] = dst[srcKey];
                }
            }
        }

        foreach (object dstKey in dst.Keys)
            if (!src.Contains(dstKey))
                src.Add(dstKey, dst[dstKey]);
    }
}

并像这样使用。

Dictionary<object, object> a = new Dictionary<object, object>();
Dictionary<object, object> b = new Dictionary<object, object>();
a.Update(b);

感谢TimChang,现在我的代码是:

public static class DictionaryExtensions
{
    public static void Update(this IDictionary src, IDictionary dst)
    {
        foreach (var key in dst.Keys)
            if (src.Contains(key))
            {
                if (src[key] is IDictionary a &&
                    dst[key] is IDictionary b)
                    a.Update(b);
                else
                    src[key] = dst[key];
            }
            else
            {
                src.Add(key, dst[key]);
            }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM