您好,我正在重构一些遗留代码。有一些代码表示从自定义类型到 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# 结构(集合或非集合)来帮助我使用一对多关系进行快速搜索。 (即我想要类似的东西 { Collection possible keys} ==> { value }
P.s 我认为每个 Custromtype 都是键并返回相同类型的简单字典并不“漂亮”
new Dictionary<string, Type>()(){
{ CustomType.Bittype, typeof(string)},
{ CustomType.Fromtotype, typeof(string)}
...
{ CustomType.Datetime, typeof(DateTime)},
{ CustomType.Date, typeof(DateTime)}
....
}
最佳答案
如果您将 string
作为默认类型,您可以使 Dictionary
更漂亮;另一个建议是将其实现为扩展方法
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/