简体   繁体   English

C# 的问题获取和设置列表集合的属性

[英]Issue with C# get and set properties for a List Collection

I need a seperate class where I want to add to some Lists anytime I set a new value.我需要一个单独的 class ,我想在设置新值时添加到一些列表中。 Using _name.Add(value) within the set method doesn't work.在 set 方法中使用 _name.Add(value) 不起作用。

I tried the following我尝试了以下

public class XMLInformation
{      
    public String BusType 
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }

} }

I use it like this:我这样使用它:

        public STARC.GlobalVariables.XMLInformation XMLInformation = new STARC.GlobalVariables.XMLInformation();
        XMLInformation.BusType = "Test";

now i get an error message (sorry error is partly in geeman)现在我收到一条错误消息(抱歉,错误部分在 geeman 中)

ISSUE问题

What am I doing wrong?我究竟做错了什么?

It can solve your issue.它可以解决你的问题。 List is not initialized and you are using it.列表未初始化,您正在使用它。 so initialize it first and then use.所以先初始化再使用。

public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType == null ? null: SubBusType.LastOrDefault();
        }
        set
        {
            if (SubBusType == null)
                SubBusType = new List<string>();
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }
}

Or或者

public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
            public List<string> SubBusType { get; set; } = new List<string>();
}

You have to Initialize the SubBusType object because at starting it will be null.您必须初始化 SubBusType object,因为在启动时它将是 null。

You can do either by creating in the constructor like below您可以通过在构造函数中创建,如下所示

 public XMLInformation()
        {
            SubBusType = new List<string>();
        }

or initiate on declaring the SubType itself like below.或开始声明 SubType 本身,如下所示。

public List<string> SubBusType { get; set; } = new List<string>();

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

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