【发布时间】:2018-02-13 07:41:30
【问题描述】:
您好,我正在重构一些遗留代码。有一些代码表示从自定义类型到 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)}
....
}
【问题讨论】:
-
字典或开关是你的朋友。有时代码并不漂亮,不妨看看微软源代码。然而美在于优雅的设计,即以健壮、可读和可维护的方式做事
-
你能控制那些
CustomTypes 吗?如果是这样,他们可以有一个只读字段Type,它返回所需的转换类型。 -
另一种选择是为
CustomType的每个包含匹配Type的成员添加一个自定义属性,然后直接使用反射获取Type,或者使用字典或类似方法准备缓存结构体。 PS。我会为所述属性的存在添加一个单元测试,因此如果CustomType成员的数量发生变化,就不会错过该属性。
标签: c# algorithm design-patterns data-structures collections