在 C# 中重构重复字典逻辑

Re-Factor duplicate dictionary Logic in C#

有没有更好的方法?如何避免重复的字典逻辑并将其放在泛型方法中?

enum department { IT, CSE, MECH, EEE, ECE }
    Dictionary<department, decimal> collegeDepartmentDecimal = new Dictionary<department, decimal>
    {
        {department.IT, 1},
        {department.CSE, 45},
        {department.MECH, 66},
        {department.EEE, 72},
        {department.ECE, 75},
    };

    Dictionary<department, string> collegeDepartmentString = new Dictionary<department, string>
    {
       {department.IT, "YES"},
        {department.CSE, "NO"},
        {department.MECH, "NULL"},
        {department.EEE, "N/A"},
        {department.ECE, null},
    };

为此我正在使用字典。

decimal d = ("something" == collegeDepartmentDecimal[collegeDepartmentDecimal.IT] ? collegeDepartmentString[collegeDepartmentDecimal.CSE] : "something");

请帮我解决这个问题。

您可以继承 Dictionary<TKey, TValue>class,如下所示:

public class MyDictionary<department, TValue> : Dictionary<department, TValue>
{
    public MyDictionary() : base() { }
    public MyDictionary(int capacity) : base(capacity) { }
}

然后将其用作:

MyDictionary<department, decimal> dic1 = new MyDictionary<department, decimal>() {
    {department.IT, 1},
    {department.CSE, 45},
    {department.MECH, 66},
    {department.EEE, 72},
    {department.ECE, 75}
};
MyDictionary<department, string> dic2 = new MyDictionary<department, string>() {
    {department.IT, "YES"},
    {department.CSE, "NO"},
    {department.MECH, "NULL"},
    {department.EEE, "N/A"},
    {department.ECE, ""}
};

在您的代码中。

使用泛型进行重构是什么意思?

如果您想将所有这些信息存储在一个字典中,您可以 a) 使用 System.Tuple b) 使用一些值类型来存储信息

一)

Dictionary<department, Tuple<decimal, string>> collegeDepartmentDecimalAndString = new Dictionary<department, Tuple<decimal, string>>
{
    {department.IT, Tuple.Create(1m, "YES")},
    {department.CSE, Tuple.Create(45m, "NO")},
    {department.MECH, Tuple.Create(66m, "NULL")},
    {department.EEE, Tuple.Create(72m, "N/A")},
    {department.ECE, Tuple.Create(75m, "")},
};