【发布时间】:2010-12-15 03:46:26
【问题描述】:
选择的解决方案
感谢大家的帮助。我决定做以下事情。
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;
}
}
我正在尝试将泛型集合 RecordCollection 转换为派生集合 PersonCollection,但出现转换异常:
RecordCollection<Person> col = this.GetRecords<Person>(this.cbPeople);
PersonCollection people = (PersonCollection)col;
我尝试这样做的原因有两个:
- 派生类(例如,PersonCollection)可以具有不应在基类中的实例方法(例如,GetLastNames)。
- GetRecords 方法是通用方法,因此我可以获得任何 Record 对象的集合。
在 C# 2.0 中解决此问题的最佳方法是什么?解决这个问题的最优雅的方法是什么?
这是 GetRecords 的签名:
public RecordCollection<T> GetRecords<T>(ComboBox cb) where T : Record, new()
这是我的基本实现:
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
}
我基于该基本实现派生了如下对象:
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>
{
}
【问题讨论】:
-
你说你想强制转换是因为派生类可能有扩展方法。您实际上是指实例方法吗?如果您真的是指扩展方法,那么像这样声明它们并没有错:method(this RecordCollection
records,...)
标签: c# c#-2.0 collections generics casting