使用泛型时的 C# 构造函数问题

标签 c# generics constructor types

请在下面查看我的代码示例:

代码已更新

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/

相关文章:

c# - 如何将图像类型转换为位图

oop - F# 对象构造函数

c++ - 错误 C2512 : no appropriate default constructor available

hibernate - 在构造函数中使用多对一集合的 SELECT NEW() - HQL

c# - ASP.NET 表单例份验证中的记住我功能不起作用

c# - 避免在 WPF 应用程序中挂起 UI

c# - 如何使用 C# 从 DIV 中抓取图像

c# - 在 C# : How to declare a generic Dictionary with a type as key and an IEnumerable<> of that type as value? 中

java通用字符串到<T>解析器

C# 如何让泛型方法等待?