带有命名/标记类型的C#字典

时间:2017-01-18 18:01:42

标签: c# dictionary collections types

我几乎到处搜索,甚至不确定它是否可能,但嘿,我想我会看到你的C#巫师可能有什么解决方案或解决方法。

TL; DR:

我有一个使用C#词典的多维集合,想要指出字典中每个字符串的用途,如下所示:

Class TestFoo:
    def testfoo1():
    """
    test description:
    step1:
    step2: 
    """

哪个当然不起作用。现在我只是评论字典。

建议,想法,想法?

4 个答案:

答案 0 :(得分:3)

您不能这样做,但您可以添加摘要。

例如:

http://localhost/interfold/products2.php?category=Aprons

这些评论将显示在intellisense中。

如果您想通过反射提取信息,可以使用custom attributes

如果只是为了可读性,可以为它创建别名:

/// <summary>
/// Dictionary<Area, Dictionary<Controller, Action>>
/// </summary>
private Dictionary<string, Dictionary<string, string>> ActionCollection;

但intellisense将显示using Area = System.String; using Controller = System.String; using Action = System.String; namespace MyApp { public class MyClass { private Dictionary<Area, Dictionary<Controller, Action>> ActionCollection; } }

答案 1 :(得分:0)

你可以将每个字符串包装在它自己的类中。然后声明和智能感知将是描述性的:

public class Area
{
    public string area { get; set; }
    public override string ToString()
    {
        return area;
    }
}
public class Controller
{
    public string controller { get; set; }
    public override string ToString()
    {
        return controller;
    }
}
public class Action
{
    public string action { get; set; }
    public override string ToString()
    {
        return action;
    }
}
private Dictionary<Area, Dictionary<Controller, Action>> ActionCollection;

答案 2 :(得分:0)

创建一个将键或值与注释配对的类:

class AnnotatedVal {
    public string Val {get;}
    public string Annotation {get;}
    public AnnotatedVal(string val, string annotation) {
        // Do null checking
        Val = val;
        Annotation = annotation;
    }
    public bool Equals(object obj) {
        var other = obj as AnnotatedVal;
        return other != null && other.Val == Val && other.Annotation == Annotation;
    }
    public int GetHashCode() {
        return 31*Val.GetHashCode() + Annotation.GetHashCode();
    }
}

private Dictionary<AnnotatedVal,Dictionary<AnnotatedVal,AnnotatedVal>> ActionCollection;

现在,您可以在词典中使用AnnotatedVal来确保隔离:

ActionCollection.Add(new AnnotatedVal("hello", "Area"), someDictionary);
if (ActionCollection.ContainsKey(new AnnotatedVal("hello", "Area"))) {
    Console.WriteLine("Yes");
} else {
    Console.WriteLine("No");
}
if (ActionCollection.ContainsKey(new AnnotatedVal("hello", "Controller"))) {
    Console.WriteLine("Yes");
} else {
    Console.WriteLine("No");
}

以上应该产生

Yes
No

因为AnnotatedVal("hello", "Area")AnnotatedVal("hello", "Controller")使用不同的注释。

答案 3 :(得分:0)

可以通过在列表中使用命名为元组的方式来实现:

private List<(string Area, List<(string Controller, string Action)>)> ActionCollection;

这是C#7.0或.NET 4.3中的功能,通过导入System.ValueTuple nuget。

Microsoft docs - tuples