部分类实例初始化空引用异常

时间:2017-04-14 13:01:19

标签: c# constructor nullreferenceexception partial-classes custom-type

我的服务包含以下参考代码:

[System.Xml.Serialization.SoapTypeAttribute(Namespace="urn:customer")]
public partial class Receipt : object, System.ComponentModel.INotifyPropertyChanged {

    private int counternoField;

    private double activekwhField;


    /// <remarks/>
    [System.Xml.Serialization.SoapElementAttribute("counter-no")]
    public int counterno {
        get {
            return this.counternoField;
        }
        set {
            this.counternoField = value;
            this.RaisePropertyChanged("counterno");
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.SoapElementAttribute("active-km")]
    public double activekm {
        get {
            return this.activekm Field;
        }
        set {
            this.activekmField = value;
            this.RaisePropertyChanged("activekm");
        }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName) {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if ((propertyChanged != null)) {
            propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}
[System.Xml.Serialization.SoapTypeAttribute(Namespace="urn:customer")]
public partial class ArrayOfReceipt : object, System.ComponentModel.INotifyPropertyChanged {

    private Receipt[] itemField;

    /// <remarks/>
    public Receipt[] item {
        get {
            return this.itemField;
        }
        set {
            this.itemField = value;
            this.RaisePropertyChanged("item");
        }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName) {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if ((propertyChanged != null)) {
            propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}

而且,当我想创建一个“ArrayOfReceipt”实例或设置一个值或访问它时,我总是遇到同样的问题:System.NullReferenceException。 这是我尝试创建时的代码:

var prev_Cons = new myService.Receipt();
prev_Cons.counterno = 1;
prev_Cons.activekm = 3265;
myService.ArrayOfReceipt prev_ConsArr = new myService.ArrayOfReceipt();
prev_ConsArr.item.SetValue(prev_Cons, 0);

不幸的是,prev_ConsArr.item始终为null,我无法对其进行初始化。请告诉我一种初始化方法并为此对象设置一些值。提前谢谢。

1 个答案:

答案 0 :(得分:0)

编写代码的方式,您可以像这样初始化prev_ConsArr.item:

prev_ConsArr.item = new Receipt[3];

这将创建一个可以容纳三个Receipt对象的新ArrayOfReceipt。您还可以为ArrayOfReceipt类创建一个初始化item的构造函数。这些方法中的任何一个都将消除您的NullReferenceException

查看使用ArrayOfReceipt类的方式,您可能需要考虑将item的类型更改为List<Receipt>。这样可以更容易地更改要存储的Receipt类的数量。

根据您要执行的操作,您可能还需要在ArrayOfReceipts中创建AddReceipt方法,并将PropertyChanged事件移至该方法。现在,PropertyChanged事件只会在您的ArrayOfReceipts类覆盖其Receipts数组时触发。