您好我正在努力重构一些遗留代码。有些代码表示从自定义类型到c#类型的“转换器”。
...
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#结构(无论是否收集)。 (即我希望看起来像 {收集可能的密钥} ==> {value}
P.s 我认为每个Custromtype都是键并返回相同类型的简单字典不是“美丽”
new Dictionary<string, Type>()(){
{ CustomType.Bittype, typeof(string)},
{ CustomType.Fromtotype, typeof(string)}
...
{ CustomType.Datetime, typeof(DateTime)},
{ CustomType.Date, typeof(DateTime)}
....
}
答案 0 :(得分:7)
如果您将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();
答案 1 :(得分:0)
德米特里的方法很好,你也可以使用这样的东西:
class Example
{
private readonly HashSet<CustomType> _stringCompatibleTypes = new HashSet<CustomType>
{
CustomType.Char, CustomType.Fromtotype, CustomType.Nclob, ...
};
private readonly HashSet<CustomType> _dateCompatibleTypes = new HashSet<CustomType>
{
CustomType.Datetime, CustomType.Timestamp3, CustomType.Timestamp6, ...
};
// Another type sets
public Type Foo(CustomType dataType)
{
if (_stringCompatibleTypes.Contains(dataType))
{
return typeof(string);
}
if (_dateCompatibleTypes.Contains(dataType))
{
return typeof(DateTime);
}
...
}
}