简体   繁体   中英

List of Generic Objects in C#

I have a simple class that includes 2 properties, one String and one a List of generic Objects. It looks like this:

public class SessionFieldViewModel
{
    private String _name;
    public String Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private List<Object> _value;
    public List<Object> Value
    {
        get { return _value ?? new List<Object>(); }
        set { _value = value; }
    }
}

Within my main code (MVC Controller) I am trying to manually populate this class. Keep in mind that when I pass data from a webform into this class using the default model binder this get populated just fine.

When Manually trying to create a record and and add it to a list I do this:

        Guid id = Guid.NewGuid();

        var _searchField = new SessionFieldViewModel();
        _searchField.Name = "IDGUID";
        Object _object = (Object)id;
        _searchField.Value.Add(_object);

        _searchFields.Fields.Add(_searchField);

When I do this I do get a populated class with a Name property of "IDGUID", but the generic lists of objects comes back null.

When I debug the code and walk it though the data seems to all be there and working as I am doing it, but when I get through and inspect _searchFields it does not show anything in the Value property of Fields.

Ideas?

Thanks in advance.

Tom tlatourelle

It appears you never set _value when it is null from the getter. Try

public List<Object> Value
{
    get { return _value ?? (_value = new List<Object>()); }
    set { _value = value; }
}

_value is never getting set to an instance of List<Object> ; it is always null. What's happening is you are returning a new List<Object> and adding an Object to it, but you're immediately discarding the newly-created List<Object> .

You need to change your definition of Value to something like this:

private List<Object> _value = new List<Object>();
public List<Object> Value
{
    get { return _value; }
    set { _value = value; }
}

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