C#构造函数使用泛型时的问题(C# Constructor Problem When Using Generics)
请参阅下面的代码示例:
代码已更新
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() }); } } }编辑更正构造函数声明! 这个代码仍然是一个问题
代码不会编译 - 它出现了很多奇怪的小错误,让我觉得这里有一个设计问题?
Please see an example of my code below:
CODE UPDATED
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() }); } } }EDIT Corrections to constructor declaration made! Still a problem with this code though
The code wont compile - it comes up with lots of strange little errors making me think that there's a design problem here?
最满意答案
正如其他人指出,你应该删除void关键字,但它仍然是不正确的。 泛型声明应该在类上,而不是构造函数中
public class ScrollableCheckboxList<TModel> where TModel : class { public ScrollableCheckboxList(...) { // ... } }As others have pointed out you should drop the void keyword, however it is still not correct. The generic declaration should be on the class, not the constructor
public class ScrollableCheckboxList<TModel> where TModel : class { public ScrollableCheckboxList(...) { // ... } }更多推荐
发布评论