请在下面查看我的代码示例:
代码已更新
public class ScrollableCheckboxList
{
public List<ScrollableCheckboxItem> listitems;
public ScrollableCheckboxList<TModel>(IEnumerable<TModel> items, string valueField, string textField, string titleField) where TModel : class
{
listitems = new List<ScrollableCheckboxItem>();
foreach (TModel item in items)
{
Type t = typeof(TModel);
PropertyInfo[] props = new [] { t.GetProperty(textField), t.GetProperty(valueField), t.GetProperty(titleField) };
listitems.Add(new ScrollableCheckboxItem
{
text = props[0].GetValue(item, null).ToString(),
value = props[1].GetValue(item, null).ToString(),
title = props[2].GetValue(item, null).ToString()
});
}
}
}
编辑 对构造函数声明进行了更正!这段代码仍然有问题
代码无法编译 - 它出现了许多奇怪的小错误,让我觉得这里存在设计问题?
最佳答案
正如其他人所指出的,您应该删除 void
关键字,但它仍然不正确。泛型声明应该在类上,而不是构造函数上
public class ScrollableCheckboxList<TModel>
where TModel : class
{
public ScrollableCheckboxList(...)
{
// ...
}
}
关于使用泛型时的 C# 构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911317/