正如其他人所解释的那样,使用您想要的确切语法是不可能的。作为一种解决方法,您可以将打字移至单独的建筑类:
public class ColumnDataBuilder
{
public static ColumnDataBuilder<T> ColumnsFor<T>(IEnumerable<T> data)
{
return new ColumnDataBuilder<T>(data);
}
}
public class ColumnDataBuilder<T> : ColumnDataBuilder
{
public IEnumerable<T> Data { get; private set; }
public ColumnDataBuilder(IEnumerable<T> data)
{
this.Data = data;
}
public ColumnData<T> Create(string name, int width, ColumnType type, Func<T, string> dataFormater)
{
return new ColumnData<T>(name, width, type, dataFormater);
}
public void populateFromData(params ColumnData<T>[] columns)
{
///...
}
}
public class ColumnData<T>
{
public ColumnData(string name, int width, ColumnType type, Func<T, string> dataFormatter)
{
}
}
然后用法可能如下所示:
var builder = ColumnDataBuilder.ColumnsFor(new List<MyDataType>());
builder.populateFromData(builder.Create("ID", 40, ColumnType.Numeric, x => x.ID.ToString()));
IEnumerable<MyDataType> data = builder.Data;
或者更接近您的示例用法(如果您想继续populateFromData
使用dataListView
),在这种情况下您可以放弃该ColumnDataBuilder<T>.populateFromData
方法(因为从您的评论看来,不可能保留在那里):
var myData = new List<MyDataType>();
var builder = ColumnDataBuilder.ColumnsFor(myData);
dataListView.populateFromData(myData, builder.Create("ID", 40, ColumnType.Numeric, x => x.ID.ToString()));
或者两全其美:
var builder = ColumnDataBuilder.ColumnsFor(new List<MyDataType>());
dataListView.populateFromData(builder.Data, builder.Create("ID", 40, ColumnType.Numeric, x => x.ID.ToString()));
编辑:考虑到您的评论,您可能不希望populateFromData
甚至可能不希望IEnumerable<T> Data
存储在 上ColumnDataBuilder
,因此您可以简化为:
public class ColumnDataBuilder<T> : ColumnDataBuilder
{
public ColumnData<T> Create(string name, int width, ColumnType type, Func<T, string> dataFormater)
{
return new ColumnData<T>(name, width, type, dataFormater);
}
}
public class ColumnDataBuilder
{
public static ColumnDataBuilder<T> ColumnsFor<T>(IEnumerable<T> data)
{
return new ColumnDataBuilder<T>();
}
}
从上面的用法:
var myData = new List<MyDataType>();
var builder = ColumnDataBuilder.ColumnsFor(myData);
dataListView.populateFromData(myData, builder.Create("ID", 40, ColumnType.Numeric, x => x.ID.ToString()));