2

我有以下非常简单和(删节的)类:

// 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?

否则,除了我认为是不好的做法的示例客户端代码的最后之外,还有什么干净的替代解决方案?

4

2 回答 2

4
List<Contact> contacts = contactDao.findUnapproved().Cast<Contact>().ToList();

只记得在文件上方添加 using linq 命名空间

于 2012-11-29T23:45:26.497 回答
2

考虑使用Enumerable.OfType Method,如果findUnapproved可能返回不同的实现IEntry并且您只想Contact从列表中获取:

List<Contact> contacts = contactDao.findUnapproved().OfType<Contact>().ToList();

至于OfType(和Cast)返回IEnumerable<T>,你需要打电话ToList来得到你想要的。

于 2012-11-29T23:49:17.240 回答