簡體   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