2009-06-03 46 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; 
     } 
    }