列出C#中的强制转换

时间:2012-11-29 23:40:31

标签: c# generics polymorphism covariance

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

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

否则,除了我的样本客户端代码的最终结果之外,什么是一个干净的替代解决方案,我认为这是一种糟糕的做法?

2 个答案:

答案 0 :(得分:4)

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

请记住在文件

上添加linq命名空间

答案 1 :(得分:2)

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

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

至于OfType(和Cast)返回IEnumerable<T>,您需要致电ToList以获得您想要的内容。