如何让这个重复的代码更优雅?

时间:2009-11-22 19:19:40

标签: c# refactoring

我在下面重复了这个代码,我假设这可以合并但是如果你注意到每个字典都是不同的通用字典:

dictionary1的类型为

Dictionary<int, ContinuousIntegrationSolution>  

而词典2的类型为:

Dictionary<int, BugTracker>

      DataTable dt = GetDataTable("CI");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            int id = Convert.ToInt32(dr["id"]);
            string name = dr["name"].ToString();
            _dictionary1[id] = new ContinuousIntegrationSolution(){Name = name};
        }

        DataTable dt1 = GetDataTable("Bug_Tracking");

        for (int i = 0; i < dt1.Rows.Count; i++)
        {
            DataRow dr = dt1.Rows[i];
            int id = Convert.ToInt32(dr["id"]);
            string name = dr["name"].ToString();
            _dictionary2[id] = new BugTracker() { Name = name };
        }

        DataTable dt2 = GetDataTable("SDLC");

        for (int i = 0; i < dt2.Rows.Count; i++)
        {
            DataRow dr = dt2.Rows[i];
            int id = Convert.ToInt32(dr["id"]);
            string name = dr["name"].ToString();
            _dictionary3[id] = new SDLCProcess() { Name = name };
        }

注意:我已修复了下面提到的一些拼写错误。

3 个答案:

答案 0 :(得分:13)

public interface INameable
{
    string Name {get;set;}
}

public static IDictionary<int, T> ReadTable<T>(string tableName)
    where T : INameable, new()
{
    DataTable dt = GetDataTable(tableName);
    var dictionary = new Dictionary<int, T>();

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dr = dt.Rows[i];
        int id = Convert.ToInt32(dr["id"]);
        string name = dr["name"].ToString();
        dictionary[id] = new T() { Name = name };
    }
    return dictionary;
}

如果你有c#4.0动态,你可以避免INameable因某些(轻微)类型安全而丢失

另一种类似于Hakon的回答,但没有暴露字典是

public IDictionary<int,T> ReadTable<T>(
    string tableName, Action<T, string> onName) 
    where T : new()
{
    var dictionary = new Dictionary<int,T>();
    DataTable table = GetDataTable(tableName);
    foreach (DataRow row in table.Rows) 
    {
        int id = Convert.ToInt32(row["id"]);
        string name = row["name"].ToString();
        var t = new T();
        onName(t, name);
        dictionary[id] = t;
    }
    return dictionary;
}

然后像这样消耗:

var ci   = ReadTable<ContinuousIntegrationSolution>("CI", 
              (t, name) => t.Name = name);  
var bt   = ReadTable<BugTracker >("Bug_Tracking", 
              (t, name) => t.Name = name);  
var sdlc = ReadTable<SDLCProcess>("SDLC", 
              (t, name) => t.Name = name);  

一种替代的,更灵活的方法,但由于类型推断而在呼叫站点使用仍然相当简单:

public IDictionary<int,T> ReadTable<T>(string tableName, Func<string,T> create) 
{
    DataTable table = GetDataTable(tableName);
    var dictionary = new Dictionary<int,T>()
    foreach (DataRow row in table.Rows) 
    {
        int id = Convert.ToInt32(row["id"]);
        string name = row["name"].ToString();
        dictionary[id] = create(name);
    }
    return dictionary;
}

然后像这样消耗:

var ci   = ReadTable("CI", 
               name => new ContinuousIntegrationSolution() {Name = name});  
var bt   = ReadTable("Bug_Tracking", 
               name => new BugTracker() {Name = name});
var sdlc = ReadTable("SDLC", 
               name => new SDLCProcess() {Name = name});

如果你采用lambda方法,我建议使用后者。

答案 1 :(得分:3)

我不会使用类似于已建议的界面,而是使用lambda函数来执行与此类似的赋值:

public void ReadTable(string tableName, Action<int, string> _setNameAction) {
    DataTable table = GetDataTable(tableName);
    foreach (DataRow row in table.Rows) {
        int id = Convert.ToInt32(row["id"]);
        string name = row["name"].ToString();
        _setNameAction(id, name);
    }
}

并调用这样的方法:

ReadTable("CI", (id, name)
    => _dictionary1[id] = new ContinuousIntegrationSolution{Name = name});  
ReadTable("Bug_Tracking", (id, name) 
    => _dictionary2[id] = new BugTracker { Name = name });  
ReadTable("SDLC", (id, name) 
    => _dictionary3[id] = new SDLCProcess { Name = name });  

答案 2 :(得分:0)

将它放在具有工厂方法的函数中以实例化id对象。像这样......

public delegate T CreateObjectDelegate<T>(string name);
public static void ProcessDataTable<T>(DataTable dt, Dictionary<int, T> dictionary, CreateObjectDelegate<T> createObj)
{
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        DataRow dr = dt.Rows[i];
        int id = Convert.ToInt32(dr["id"]);
        string name = dr["name"].ToString();
        dictionary[id] = createObj(name);
    }
}

static void Main(string[] args)
{
    var dt = new DataTable();
    var dictionary = new Dictionary<int, BugTracker>();
    ProcessDataTable<BugTracker>(dt, dictionary, (name) => { return new BugTracker() { Name = name }; });
}