简体   繁体   English

C#中的通用对象列表

[英]List of Generic Objects in C#

I have a simple class that includes 2 properties, one String and one a List of generic Objects. 我有一个简单的类,包括2个属性,一个String和一个通用对象列表。 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. 在我的主代码(MVC控制器)中,我试图手动填充此类。 Keep in mind that when I pass data from a webform into this class using the default model binder this get populated just fine. 请记住,当我使用默认的模型绑定器将数据从webform传递到此类时,这将得到很好的填充。

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. 当我这样做时,我得到一个具有Name属性“IDGUID”的填充类,但通用的对象列表返回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. 当我调试代码并遍历它时,虽然数据似乎都在那里并正在我正在做的工作,但是当我通过并检查_searchFields时它没有在Fields的Value属性中显示任何内容。

Ideas? 想法?

Thanks in advance. 提前致谢。

Tom tlatourelle 汤姆tlatourelle

It appears you never set _value when it is null from the getter. 当getter为null时,你似乎永远不会设置_value 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> ; _value永远不会被设置为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> . 发生的事情是您返回一个新的List<Object>并向其添加一个Object ,但是您立即丢弃了新创建的List<Object>

You need to change your definition of Value to something like this: 您需要将Value的定义更改为以下内容:

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

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

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