分配属性时使用C#空引用

时间:2019-12-17 19:26:28

标签: c# properties

虽然在同一个命名空间中,但是我在属性上却有一系列不太复杂的类,就像这样:

    public class WholeBase
{
    public SomeHeaders Headers { get; set; }
    public SomeBody Body { get; set; }
}

public partial class SomeHeaders
{
    public string HeaderOne { get; set; } = "N/a";
    public string HeaderTwo { get; set; } = "N/a";
}

public partial class InSet
{
    public string AllForward { get; set; } = "NO";
    public string Available { get; set; } = "NO";
}

public partial class SomeBody
{
    public InSet MySet { get; internal set; }
    public Boolean CombinedServiceIndicator { get; set; } = false;
    public int FrequencyPerDay { get; set; } = 1;
    public string ValidUntil { get; set; } = "9999-12-31";
}

现在,在Main内部,我尝试提供值,并得到System.NullReferenceException:'对象引用未设置为对象的实例。' 有什么想法吗?

分配值:

    class Program
{
    //...
    static void Main(string[] args)
    {
        WholeBase NewThing = new WholeBase();

        NewThing.SomeHeaders.HeaderOne = "First header Value";

        Console.WriteLine(NewThing.SomeHeaders.HeaderOne.ToString());   //System.NullReferenceException: 'Object reference not set to an instance of an object.'
        Console.ReadLine();

        NewThing.SomeHeaders.HeaderTwo = "Second header Value";
        NewThing.Body.MySet.AllForward = "YES";
        NewThing.Body.MySet.Available = "YES";
        NewThing.Body.CombinedServiceIndicator = false;
        NewThing.Body.FrequencyPerDay = 10;
        NewThing.Body.ValidUntil = "2019-12-31";
    }
}

0 个答案:

没有答案