時,請參閱下面我的代碼示例:C#構造函數問題使用泛型
CODE修訂
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()
});
}
}
}
編輯 更正構造函數聲明訂做!這個代碼仍然存在問題
該代碼不會編譯 - 它出現了很多奇怪的小錯誤,讓我覺得這裏有一個設計問題?
一個愚蠢的疏忽!感謝您指出了這一點。 – Jimbo 2010-05-26 08:46:00
我已經更新了上面的代碼,它仍然不會編譯,我不明白爲什麼(從編譯器沒有明確的錯誤!) – Jimbo 2010-05-26 08:51:49
好吧,發現問題,類聲明必須定義通用對象TModel,而不是構造函數。感謝您的輸入。 – Jimbo 2010-05-26 08:57:40