猿问

Getter返回NULL C#

使用getter访问属性时,我得到NULL。我已将其更改为公开,以测试其他所有功能是否正常运行,是的,没有其他问题。


HT省级


public string provinceCode;


public string ProvinceCode

    {

        get; set;

    }

形式


    public Form1()

    {

        //HTGetProvinces() returns a list of provinces

        InitializeComponent();

        List<HTProvince> provinceList =

            HTProvince.HTGetProvinces();


        foreach (HTProvince x in provinceList)

        {

            //Works. Adds items the province code property of for each item to my list

            provincesListBox.Items.Add(x.provinceCode); 

            //throws null exception. Doesn't work

            provincesListBox.Items.Add(x.ProvinceCode);

        }

    }


慕尼黑5688855
浏览 174回答 3
3回答

侃侃尔雅

那是一个坏习惯。您必须将字段“ provinceCode”设为私有private string provinceCode;您的媒体资源只能是公开的,只能访问。public string ProvinceCode&nbsp; {&nbsp; &nbsp; get&nbsp;&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; return provinceCode;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;set&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;provinceCode = value;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;}public Form1(){&nbsp; &nbsp; //HTGetProvinces() returns a list of provinces&nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; List<HTProvince> provinceList =&nbsp; &nbsp; &nbsp; &nbsp; HTProvince.HTGetProvinces();&nbsp; &nbsp; foreach (HTProvince x in provinceList)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Works. Adds items the province code property of for each item to my list&nbsp; &nbsp; &nbsp; &nbsp; provincesListBox.Items.Add(x.ProvinceCode);&nbsp;&nbsp; &nbsp; }}

慕桂英4014372

这是正确的行为,您没有为此属性或设置值返回任何值,因此它为null。&nbsp; &nbsp; &nbsp;public string ProvinceCode&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;get; set;&nbsp; &nbsp; }如果您想返回省号&nbsp; private string provinceCode;&nbsp; public string ProvinceCode&nbsp; {&nbsp; &nbsp; get&nbsp;&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; return provinceCode;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;set&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;provinceCode = value;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;}
随时随地看视频慕课网APP
我要回答