2009-06-03 40 views
1

下面是一些代碼,嚴重降低版本我有如何減少使用lambda參數時的類型聲明?

public class DataInfo<T> 
{ 
    public DataInfo(string description, Func<T, object> funcToGetValue) 
    { 
     this.description = description; 
     this.funcToGetValue= funcToGetValue; 
    } 

    public readonly string description; 
    public readonly Func<T, object> funcToGetValue; 
} 

public class DataType1 
{ 
    public int fieldA { get; set; } 
    public string fieldB { get; set; } 
} 

public class CurrentUse 
{ 
    static List<DataInfo<DataType1>> data1 = new List<DataInfo<DataType1>>() 
    { 
     new DataInfo<DataType1>("someStuff", data => data.fieldA), 
     new DataInfo<DataType1>("someOtherStuff", data => data.fieldB) 
    }; 
} 

(有很多種類,而且不用擔心並非一切都是公衆確實!)

這是工作,是OK儘管如此,但事實是我不得不繼續重複new DataInfo<DataType1>使我困擾。

我試圖創建DataInfo的非通用輔助優化版本爲我創建的對象爲使

public class DataInfo 
{ 
    public static DataInfo<T> Create<T>(string description, Func<T, object> func) 
    { 
     return new DataInfo<T>(description, func); 
    } 
} 
public class DesiredUse 
{ 
    static List<DataInfo<DataType1>> data1 = new List<DataInfo<DataType1>>() 
    { 
     DataInfo.Create("someStuff", data => data.fieldA), 
     DataInfo.Create("someOtherStuff", data => data.fieldB) 
    }; 
} 

但是,這並不因爲它的工作編譯器無法解析FIELDA & fieldB,因爲它不能推斷出類型數據的。

任何想法如何擺脫重複的類型信息?我不介意做修改,只要我結束了DataInfos

列表

回答

3

我想創建一個生成器類:

public sealed class DataInfoListBuilder<T> : IEnumerable 
{ 
    private readonly List<DataInfo<T>> list = new List<DataInfo<T>>(); 

    public void Add(string description, Func<T, object> function) 
    { 
     list.Add(DataInfo.Create<T>(description, function)); 
    } 

    public List<DataInfo<T>> Build() 
    { 
     return list; 
    } 

    public IEnumerator GetEnumerator() 
    { 
     throw new InvalidOperationException 
      ("IEnumerator only implemented for the benefit of the C# compiler"); 
    } 
} 

然後用它作爲:

static List<DataInfo<DataType1>> data1 = new DataInfoListBuilder<DataType1> 
{ 
    { "someStuff", data => data.fieldA }, 
    { "someOtherStuff", data => data.fieldB } 
}.Build(); 

我沒有測試過,但我認爲這應該起作用。你可以把它內DataInfo非泛型類型,在這種情況下,你使用:

static List<DataInfo<DataType1>> data1 = new DataInfo<DataType1>.Builder 
{ ... }.Build(); 
+0

感謝喬恩,這工作太棒了! – Argos 2009-06-03 13:42:50

0

您可以從可能繼承表>,並提供一個專門的加入方法:

public class SpecialList<T> : List<DataInfo<T>> 
{ 
    public void Add(string description, Func<T, object> func) 
    { 
     base.Add(new DataInfo<T>(description, func)); 
    } 
} 

然後,你可以這樣使用它:

public class CurrentUse 
{ 
    public static SpecialList<DataType1> Data1 
    { 
     get 
     { 
      SpecialList<DataType1> list = new SpecialList<DataType1>(); 
      list.Add("someStuff", data => data.fieldA); 
      list.Add("someOtherStuff", data => data.fieldB); 

      return list; 
     } 
    }