我有一个类型 MyStudent
还有一个该类型的接口Student为什么List<MyStudent> list的list不能转成List<Student>就是 list as List<Student>得到的结果是null。
还有一个该类型的接口Student为什么List<MyStudent> list的list不能转成List<Student>就是 list as List<Student>得到的结果是null。
虽然MyStudent实现了Student
但是List<MyStudent>跟List<Student>并没有任何继承关系。如果要转换,写个方法挨个对象装换吧。
虽然MyStudent实现了Student
但是List<MyStudent>跟List<Student>并没有任何继承关系。如果要转换,写个方法挨个对象装换吧。
打错了,挨个对象转换吧。
类似于 public static List<Student> Convert2ParentList(List<MyStudent> students)
{
List<Student> result = new List<Student>();
foreach(MyStudent mS in students)
{
result.Add(ms);
} return result;
}
这个应该……编译不过去吧。
[/Quote]
我中间变成了object
public interface Student
{
string Id { get; }
} public class MyStudent : Student
{
private string id;
public string Id
{
get
{
if (id == null)
{
id = Guid.NewGuid().ToString();
}
return id;
}
}
}foreach(Student s in (List<Student>)list).....//这个list是一个object,其实是List<MyStudent>但是这个foreach怎么也进不去啊。
接口不能实例化,只能用于引用。
List<Student> studentList = new List<MyStudent>();
只能这么整的。注:
接口和对象都不可以实例化,但是接口可以引用。例如有一个实现了IPrintable 的 AA类,虽然不可以创建起对象,但可以这样做:
IPrintable xxx = new AA();
在这里 xxx就叫做引用,在这个例子中就是指某个AA对象