Arm*_*rat 1 c# generics collections casting c#-2.0
选择解决方案
感谢大家的帮助.我决定做以下事情.
public static class PersonCollection
{
public static List<string> GetNames(RecordCollection<Person> list)
{
List<string> nameList = new List<string>(list.Count);
foreach (Person p in list)
{
nameList.Add(p.Name);
}
return nameList;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将一个通用集合RecordCollection转换为派生集合PersonCollection,但是我得到了一个强制转换异常:
RecordCollection<Person> col = this.GetRecords<Person>(this.cbPeople);
PersonCollection people = (PersonCollection)col;
Run Code Online (Sandbox Code Playgroud)
我试图这样做的原因有两个:
在C#2.0中解决这个问题的最佳方法是什么?解决这个问题最优雅的方法是什么?
这是GetRecords的签名:
public RecordCollection<T> GetRecords<T>(ComboBox cb) where T : Record, new()
Run Code Online (Sandbox Code Playgroud)
这是我的基本实现:
public abstract class Record : IComparable
{
public abstract int CompareTo(object other);
}
public class RecordCollection<T> : ICollection<T> where T : Record, new()
{
private readonly List<T> list;
public RecordCollection()
{
this.list = new List<T>();
}
// Remaining ICollection interface here
}
Run Code Online (Sandbox Code Playgroud)
我基于该基本实现派生了对象,如下所示:
public class Person : Record
{
public Person()
{
// This is intentionally empty
}
public string Name
{
get;
set;
}
public override int CompareTo(object other)
{
Person real = other as Person;
return this.Name.CompareTo(real.Name);
}
}
public class PersonCollection : RecordCollection<Person>
{
}
Run Code Online (Sandbox Code Playgroud)
您的方法不起作用,因为强制转换不会将一个类的实例转换为另一个类的实例.
你没有给出GetRecords <>方法的代码,但可能是GetRecords返回RecordCollection,而不是PersonCollection(它在代码中的某处有新的RecordCollection,不是吗?).
除非此特定实例实际上是PersonCollection,否则无法将RecordCollection转换为PersonCollection.主要是因为它没有这些额外的方法.
这就像
SomeClass obj=new SomeClass();
DerivedClass o=(DerivedClass)obj; //throws exception
Run Code Online (Sandbox Code Playgroud)