【发布时间】:2018-08-15 05:11:05
【问题描述】:
我有一个泛型类,它只包含一个列表类型的数据成员。现在,我想使用我的 main 方法中该泛型类的对象初始化程序向该列表添加值。
这是我的通用类
class GenericStore<T>
{
public List<T> allData = new List<T>();
}
这里是我的入口点
class Program
{
static void Main(string[] args)
{
GenericStore<Student> studentData = new GenericStore<Student>()
{
// I Have Write This Which Gives me Error
/*allData = new Student(new Guid(), "Subhashis Pal"),
allData = new Student(new Guid(), "x"),
allData = new Student(new Guid(), "Y"),
allData = new Student(new Guid(), "Z")*/
};
}
}
这是我的学生课
class Student
{
private Guid id;
private string name;
public Student(Guid id, string name)
{
this.id = id;
this.name = name;
}
}
【问题讨论】:
-
你为什么不向你的商店添加一个构造函数,它接受一个类型为 T 的参数并将一个学生传递给它?
-
哪个错误?也请提及。
-
您确实应该编辑您的帖子并添加错误消息。实际上它信息量很大:
Cannot implicitly convert type 'Student' to 'System.Collections.Generic.List<Student>'。这意味着您的类型不匹配。如果您开始研究compiler error code,您可以自己解决这个问题。 :) -
实际上研究了你问题的整个标题给了我this as the first result。发布的答案在那里。唯一的区别是他们使用的是猫;)而不是学生
-
实际上我很困惑,因为 allData 是一个类的成员,我正在使用对象初始化程序。我理解 Cat 的例子,但我应该弄清楚。谢谢。 :)
标签: c# generics object-initializers