C# 中的列表、多态性和转换问题
下午好,我希望传输实现某个接口(“IRecord”)的对象列表,我所做的就是在新列表中过滤在以下情况“IEntry”中实现该接口的对象,直到有没问题,但是,当我尝试将过滤列表强制转换为“IList”类型以使用最后一个具有的属性时遇到问题,这会产生异常,我该如何解决这个问题,有没有办法避免去遍历整个列表,并创建一个新列表 再次?
interface IRecord
{
string Details { get; set; }
}
interface IEntry : IRecord
{
decimal TotalValue { get; set; }
}
interface IEgress : IRecord
{
string Type { get; set; }
}
class Entry : IEntry
{
public string Details { get; set; }
public decimal TotalValue { get; set; }
public void Foo() { }
}
class Egress : IEgress
{
public string Details { get; set; }
public string Type { get; set; }
}
这是我尝试执行的代码
var records = new List<IRecord>() { new Entry() { Details = "foo" }, new Egress() { Details = "bar" } };
var filteredList = records.Where(entry => entry is Entry).ToList();
var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);
Good afternoon, I am looking to transfer a list of objects that implement a certain interface ("IRecord"), what I do is to filter in a new list the objects that implement the interface in the following case "IEntry", until there is no problem, however, I have problems when I try to caste the filtered list to the type "IList" to use the properties that this last one has, this produces an exception, how can I solve this, Is there a way to avoid going through the whole list, and create a new one again?
interface IRecord
{
string Details { get; set; }
}
interface IEntry : IRecord
{
decimal TotalValue { get; set; }
}
interface IEgress : IRecord
{
string Type { get; set; }
}
class Entry : IEntry
{
public string Details { get; set; }
public decimal TotalValue { get; set; }
public void Foo() { }
}
class Egress : IEgress
{
public string Details { get; set; }
public string Type { get; set; }
}
This is the code I am trying to execute
var records = new List<IRecord>() { new Entry() { Details = "foo" }, new Egress() { Details = "bar" } };
var filteredList = records.Where(entry => entry is Entry).ToList();
var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论中已经提到的,您可以在调用
ToList()
之前Cast
查询varfilteredList =records.Where(entry =>entry is Entry).Cast
IEntry>().ToList();
所以最终结果是
我也向您的 Entry 类型添加了一个值,然后您可以证明您的代码有效:D
这里是有关继承的 Microsoft 文档的链接
As already mentioned in comments you can
Cast
your query before callingToList()
var filteredList = records.Where(entry => entry is Entry).Cast<IEntry>().ToList();
So the end result would be
I added a value to your Entry type too, which then allows you to prove your code works :D
Here is a link to Microsoft document on inheritance