简体   繁体   English

C#:添加到类型SomeClass的列表

[英]C#: Adding to a List of Type SomeClass

I have this class: 我有这个课:

public class Lockbox
{
    string lockbox { get; set; }
    int polling_interval { get; set; }
}

In another class I made a List of Type Lockbox: 在另一堂课中,我列出了类型的密码箱:

var monitor_lockboxes = new List<Lockbox>();

Now how do I add entries to the list? 现在如何将条目添加到列表中? Can I do this?: 我可以这样做吗?:

monitor_lockboxes.Add(...);

But it does not take 2 arguments. 但这不需要两个参数。

But it does not take 2 arguments. 但这不需要两个参数。

Well no, it wouldn't. 好吧,不会。 It takes one argument, of type Lockbox . 它需要一个参数,类型为Lockbox

It sounds like you want something like: 听起来您想要这样的东西:

var newBox = new Lockbox { lockbox = "foo", polling_interval = 10 };
monitor_lockboxes.Add(newBox);

You can do it in a single statement, of course - I've only separated it out here for clarity. 当然,您可以在一条语句中完成此操作-为了清楚起见,这里仅将其分开。

(I'd also strongly advise you to change your naming to follow .NET conventions .) (我也强烈建议您更改命名方式以遵循.NET约定 。)

The following would work: 以下将起作用:

monitor_lockboxes.Add(new Lockbox { lockbox = "Foo", polling_interval = 42 } );

This uses the the Object Initializer syntax. 这使用对象初始化器语法。 For this to work, the properties on Lockbox have to be public . 为此, Lockbox上的属性必须是public

Another approach would be to provide a constructor to Lockbox that takes the values of the properties: 另一种方法是为Lockbox提供一个使用属性值的构造函数:

public class Lockbox
{
    public Lockbox(string lockbox, int pollingInterval)
    {
        this.lockbox = lockbox;
        this.polling_interval = pollingInterval;
    }

    public string lockbox { get; set; }
    public int polling_interval { get; set; }
}

Now you can use it like this: 现在您可以像这样使用它:

monitor_lockboxes.Add(new Lockbox("Foo", 42));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM