如何将List <t>转换为T </t>的派生类

时间:2014-01-04 11:57:19

标签: c#

AnswerRecords返回DnsRecordBase的列表:

List<DnsRecordBase> _Records = _DnsMessage.AnswerRecords;

MxRecord继承自DnsRecordBase

public class MxRecord : DnsRecordBase

如何投标_Records有一个MxRecord列表?

我试过了:

List<MxRecord> _Records = (MxRecord)_DnsMessage.AnswerRecords;
List<MxRecord> _Records = _DnsMessage.AnswerRecords as MxRecord;

此语法不起作用:)

1 个答案:

答案 0 :(得分:4)

如果_Records中的所有元素都是MxRecord

,这应该有用
List<DnsRecordBase> _Records = _DnsMessage.AnswerRecords;
List<MxRecord> _MxRecords = _Records.Cast<MxRecord>().ToList();