C#构造函数使用泛型时的问题(C# Constructor Problem When Using Generics)

编程入门 行业动态 更新时间:2024-10-09 15:17:06
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(...) { // ... } }

更多推荐

本文发布于:2023-07-09 10:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   泛型时   Constructor   Problem   Generics

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!