【问题标题】:How would I make this dynamic list in C# 4.0?我将如何在 C# 4.0 中制作这个动态列表?
【发布时间】:2011-08-27 17:30:43
【问题描述】:

如果不将对象序列化为字节数组,这可能是不可能的,但我想要一个对象集合,其中唯一的公共属性将是 intbool

public class Speakers : IStereoComponents
{
     public int Id { get; set; }
     public bool RemoveMe { get; set; }
     public string SomethingElse { get; set; }
}

public class Receiver : IStereoComponents
{
    public int Id { get; set; }
    public bool RemoveMe { get; set; }
    public IList<string> Buttons { get; set; }
}

public interface IStereoComponents
{
     int Id { get; set; }
     bool RemoveMe { get; set; }
}

我想要做的是能够将这些项目添加到列表或字典中,并根据 Id 和 RemoveMe 字段删除或添加它们。我希望能够做类似的事情:

foreach(组件中的var组件)component.RemoveMe == true;

有没有简单的方法来做到这一点?我能想到的唯一方法是使用反射,将所有内容序列化为一个字节 [],除了 Id 和 RemoveMe 属性。这将是一件苦差事,我希望有一个花哨的 C# 4.0 来做这件事?还是我完全遗漏了什么?

【问题讨论】:

    标签: c# c#-4.0


    【解决方案1】:

    无需反思!只需创建一个List&lt;IStereoComponents&gt;

    var components = new List<IStereoComponents>();
    components.Add(new Speakers { Id = 1, RemoveMe = false, SomethingElse = "100W" });
    components.Add(new Receiver { Id = 2, RemoveMe = false, Buttons = new List<string>() });
    

    然后,您可以随意循环它们:

    foreach (var component in components)
    {
        if (listOfIdsToRemove.Contains(component.Id))
            component.RemoveMe = true;
    }
    

    接口的美妙之处在于您并不真正关心对象还能做什么:只要它完成接口要求的工作,就足够了。

    【讨论】:

    • 还要在界面中去掉RemoveMe的public修饰符,在foreach中将==改为=。
    • 仅供参考,如果 List 类不支持您的需求 System.Collections.Generic 命名空间有一大堆类型化集合,可能会提供您需要的额外方法。
    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 2011-12-08
    • 1970-01-01
    • 2023-02-01
    • 2013-12-14
    • 2016-07-20
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多