嗨,
我正试图找到如何改进此代码的方法.我想从CreateAttributes方法中删除"if"语句.如果此属性满足某些条件,则此方法的主要思想是将属性添加到列表
internal class FildMap { public string ExactTargetFild { get; set; } public string DbFild { get; set; } public Type Type { get; set; } } internal static class FildMapProcessor { private static readonly ListMap = new List (); static FildMapProcessor() { if(Map.Count == 0) { Map.Add(new FildMap {ExactTargetFild = "Address 1", DbFild = "Address1", Type = typeof (string)}); Map.Add(new FildMap { ExactTargetFild = "Date of birth", DbFild = "DateOfBirth", Type = typeof(DateTime) }); Map.Add(new FildMap { ExactTargetFild = "Wine Beer", DbFild = "pref_WineBeerSpirits", Type = typeof(bool) }); ......... } } public static Attribute[] CreateAttributes(this DataRow row) { var attributes = new List (); foreach (var item in Map) { if (item.Type == typeof(string)) { var value = row.Get (item.DbFild); if (value != null) attributes.Add(new Attribute{Name = item.ExactTargetFild, Value = value}); } if (item.Type == typeof(DateTime)) { var value = row.Get (item.DbFild); if (value != DateTime.MinValue) attributes.Add(new Attribute { Name = item.ExactTargetFild, Value = value.ToString("dd/MM/yyyy") }); } if (item.Type == typeof(bool)) { if (row.Contains(item.DbFild)) { var value = row.Get (item.DbFild); attributes.Add(new Attribute { Name = item.ExactTargetFild, Value = value.ToString() }); } } } return attributes.ToArray(); } }
谢谢,
你可以在这里使用多态
internal abstract class FildMap { public string ExactTargetFild { get; set; } public string DbFild { get; set; } public abstract ListGetAttributes(DataRow row); } internal class StringFildMap : FildMap { public override List GetAttributes(DataRow row) { //string specific stuff } }
为其他类型创建其他类
public static Attribute[] CreateAttributes(this DataRow row) { var attributes = new List(); foreach (var item in Map) { attributes.AddRange(item.GetAttributes(row)); } return attributes.ToArray(); }