简体   繁体   中英

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 .

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 .)

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 .

Another approach would be to provide a constructor to Lockbox that takes the values of the properties:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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