提问人:Chaoguo0 提问时间:12/5/2016 最后编辑:sujith karivelilChaoguo0 更新时间:12/5/2016 访问量:129
如何在没有构造函数的情况下访问另一个类中类中定义的数组?
How to access array defined in class in another class without constructor?
问:
我有我正在使用的 API 给出的这段代码。
public partial class getMerchant : object, System.ComponentModel.INotifyPropertyChanged
{
private int[] iMerchantIdField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("iMerchantId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public int[] iMerchantId
{
get
{
return this.iMerchantIdField;
}
set
{
this.iMerchantIdField = value;
this.RaisePropertyChanged("iMerchantId");
}
}
}
现在我正在尝试创建此类的对象并运行它:
private void btnShowResult_Click(object sender, EventArgs e)
{
Awin.ApiPortTypeClient client = new Awin.ApiPortTypeClient();
UserAuthentication userAuthentication = new UserAuthentication();
userAuthentication.sApiKey = "111";
getMerchant merchant = new getMerchant();
merchant.iMerchantId[0] = 2518;
merchant.iMerchantId[1] = 3030;
var response = client.getMerchant(userAuthentication, merchant);
lblResult.Text = response[0].sName.ToString();
}
但是每当我尝试运行它时,当编译器命中行merchant.iMerchantId[0] = 2518时,它都会给出nullreferenceexception; 到目前为止,我的理解是这个 iMerchantId[] 尚未声明。但问题还在于我找不到如何声明它的答案。
我很感谢我能得到的任何帮助。
答:
2赞
sujith karivelil
12/5/2016
#1
为了解决这个问题,使用所需的索引初始化备份属性,这意味着属性定义将如下所示:
private int[] iMerchantIdField= new int[2];
不需要更改 Public 属性,尝试使用当前代码,它不会出现以前的错误,因为数组的边界现在通过这些备份属性进行定义和初始化。
附注事项 :如果处理数组的 List,则必须通过 backup 属性实例化列表,否则将抛出 NullException。在这种情况下,声明将是:
private List<int> iMerchantIdField= new List<int>();
评论
0赞
lc.
12/5/2016
我还会重新审视这是否真的应该是一个数组或一个.List
0赞
Chaoguo0
12/6/2016
我将属性更改为:private int[] iMerchantIdField= new int[2];nullreferenceexception 不再弹出,但我现在收到此错误代码:“System.ServiceModel.FaultException” 我该如何处理?
评论