簡體   English   中英

C#中的列表轉換

[英]List Casting in C#

我有以下非常簡單的(精簡的)類:

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

否則,除了我認為是不好的做法的示例客戶端代碼的最后,還有什么干凈的替代解決方案?

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

只記得在文件上方使用linq命名空間添加

考慮使用Enumerable.OfType方法 ,如果findUnapproved可能返回IEntry不同實現,並且您只想從列表中獲取Contact

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

至於OfType (和Cast )返回IEnumerable<T>您需要調用ToList以獲得所需的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM