下面是一些代碼,嚴重降低版本我有如何減少使用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
列表
感謝喬恩,這工作太棒了! – Argos 2009-06-03 13:42:50