【问题标题】:Is there a way to generically return a value from a set of dictionaries with different value types?有没有办法从一组具有不同值类型的字典中返回一个值?
【发布时间】:2019-02-26 21:49:33
【问题描述】:

我在代码中不断遇到的问题是这样的,

public Dictionary<string, int> NumericProperties { get; set; }
public Dictionary<string, string> TextProperties { get; set; }
public Dictionary<string, string[]> CollectionProperties { get; set; }
public Dictionary<string, KeyValue[]> DependencyProperties { get; set; }

public T GetProperty<T>(string name)
{
  //find out which property dictionary and return value
}

有没有办法在 C# 中有效地做到这一点?我的另一个想法是创建一个&lt;string, object&gt; 类型的Dictionary 并使用它(我知道没有generic Dictionary 类型我也可以使用)然后它只是一个返回一个可以是Pattern Matched 的对象以查找其原始类型。

这个选项的问题是变量的boxingun-boxing 以及它失去了它的通用性。我的另一个选择是为Property 创建一个抽象基类,但是因为每个属性都包含一个名称-值对,因此需要再次使用generics,我们遇到了尝试动态返回不同Types 的相同问题.

任何帮助将不胜感激!谢谢。

【问题讨论】:

  • 是否装箱和拆箱对您来说真的是个问题?因为您可以使用Dictionary&lt;string, object&gt; 并让GetProperty&lt;T&gt; 返回(T)dict[name]。据我所知,Umbraco 如何处理从其页面属性字典返回的属性。
  • 简单实现object GetProperty(string name)
  • dict&lt;string, object&gt; 看起来是最强大的解决方案。我建议您不要太在意装箱/拆箱,除非它是热门路径。
  • 感谢 cmets 伙计们,只是想检查一下我没有错过一个非常简单的方法!将使用对象字典选项,谢谢!

标签: c# generics pattern-matching


【解决方案1】:

您可以创建一个可用字典的字典。要么手动初始化已知的字典类型,要么让它自动执行SetProperty 方法。

public static Dictionary<Type, object> PropertDicts { get; } = new Dictionary<Type, object>();

public static void SetProperty<T>(string name, T value)
{
    Dictionary<string, T> typedDict;
    if (PropertDicts.TryGetValue(typeof(T), out object dict)) {
        typedDict = (Dictionary<string, T>)dict;
    } else {
        typedDict = new Dictionary<string, T>();
        PropertDicts.Add(typeof(T), typedDict);
    }
    typedDict[name] = value;
}

public static T GetProperty<T>(string name)
{
    if (PropertDicts.TryGetValue(typeof(T), out object dict)) {
        var typedDict = (Dictionary<string, T>)dict;
        if (typedDict.TryGetValue(name, out T value)) {
            return value;
        }
    }
    return default(T);
}

但泛型只有在您事先知道属性的类型时才有效。对于完全动态的场景,泛型是无用的。

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多