我有以下非常简单和(删节的)类:
// IEntry interface
public interface IEntry {
long Id { get; set; }
string Name { get; set; }
}
// IEntry implementation
public class Contact : IEntry {
public long Id { get; set; }
public string Name { get; set; }
}
// DAO Interface
public interface IEntryDao {
List<IEntry> findUnapproved();
}
// abstract base class
public abstract class AbstractEntryDao : IEntryDao {
public virtual List<IEntry> findUnapproved() {
List<IEntry> entries = new List<IEntry>();
// ... default load logic
return entries;
}
}
// ContactDao implementation
public class ContactDao : AbstractEntryDao {
public override List<IEntry> findUnapproved() {
List<IEntry> contacts = new List<IEntry>();
// ... custom load logic for Contact
return contacts;
}
}
// sample client code
public void testFindUnapproved() {
ContactDao contactDao = new ContactDao();
List<IEntry> contacts = contactDao.findUnapproved(); // <--- this line works (but not what I want)
List<Contact> contacts = contactDao.findUnapproved(); // <--- this does not work (which makes sense)
List<Contact> contacts = contactDao.findUnapproved() as List<Contact>; // <--- this does not work
// here is how i compensate for this problem... but i do not like this
List<Contact> list = new List<Contact>();
foreach (IManageableEntry contact in contacts) {
list.Add(contact as Contact);
}
}
我想要的是一种非常简单的方法(或者可能在 Dao 接口和抽象类中使用泛型)
List<Contact> contacts = contactDao.findUnapproved(); // <--- can I achieve this using generics in .NET 3.5?
否则,除了我认为是不好的做法的示例客户端代码的最后之外,还有什么干净的替代解决方案?