你好,我正在重构一些遗留代码有些代码表示从自定义类型到c类型的“converter”。

          ...
           if (dataType == CustomType.Bit)
            {
                return typeof(bool);
            }
            else if (dataType == CustomType.Bittype ||
                dataType == CustomType.Char ||
                dataType == CustomType.Fromtotype ||
                dataType == CustomType.Mdcintervaltype ||
                dataType == CustomType.Nclob ||
                dataType == CustomType.Nchar ||
                dataType == CustomType.Ntext ||
                dataType == CustomType.Nvarchar ||
                dataType == CustomType.Nvarchar2 ||
                dataType == CustomType.Varchar ||
                dataType == CustomType.Varchar2)
            {
                return typeof(string);
            }
            else if (dataType == CustomType.Date ||
                dataType == CustomType.Datetime ||
                dataType == CustomType.Timestamp3 ||
                dataType == CustomType.Timestamp6)
            {
                return typeof(DateTime);
            }
            else if (dataType == CustomType.Decimal ||
                dataType == CustomType.Money ||
                dataType == CustomType.Number ||
                dataType == CustomType.Numeric)
            {
                return typeof(decimal);
            }

...
问:我正在寻找一些C结构(是否收藏),可以帮助我快速搜索一对多的关系(例如,我想要类似{Collection possible keys}==>{value}的内容)
另外,我认为简单的字典中每个custromtype都是key并返回相同的类型,这并不是“美好的”
new Dictionary<string, Type>()(){
    { CustomType.Bittype, typeof(string)},
    { CustomType.Fromtotype, typeof(string)}
     ...
    { CustomType.Datetime,  typeof(DateTime)},
    { CustomType.Date, typeof(DateTime)}
    ....
}

最佳答案

如果将Dictionary作为默认类型,则可以使string更漂亮;另一个建议是将其作为扩展方法实现

 public static class CustomTypeExtensions {
   private static Dictionary<CustomType, Type> s_Map = new Dictionary<CustomType, Type>() {
     {CustomType.Datetime,  typeof(DateTime)},
     {CustomType.Date, typeof(DateTime},
     ...
   };

   public static Type ToType(this CustomType value) {
     if (s_Map.TryGetValue(value, out var result))
       return result;
     else
       return typeof(string); // when not found, return string
   }
 }

....
var custom = CustomType.Bittype;

...

Type t = custom.ToType();

关于c# - 适当的C#集合,可通过多个键快速搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48761725/

10-11 19:31