[英]Class with properties but few properties not assigned
我有C#类,我有不同的属性。
public class Employee
{
public int ID;
public string Name;
public int Age;
}
WebServices pp=new WebServices();
Employee emp= pp.GetEmpInfo();
//pp is an instance of webservices which is web referenced in the app.
emp.ID=100;
emp.Age=25;
我不从GetEmpInfo()
分配/获取名称的返回值,这会引发任何异常吗?
如果您有一个包含10个属性的类,却没有分配几个属性,那么它将破坏应用程序吗?
请分享您的想法。 生产中有一些代码,我不确定结果如何,因此请检查。
如果您的Web服务方法返回null
:
[WebMethod]
public Employee GetEmpInfo()
{
return null;
}
然后以下将引发NullReferenceException :
emp.ID = 100;
因为不会分配emp
变量。
为了避免这种情况,请在访问变量的属性(或在您的情况下为公共字段)之前验证是否已分配变量:
Employee emp = pp.GetEmpInfo();
if (emp != null)
{
emp.ID = 100;
emp.Age = 25;
}
初始构造之后(在调用构造函数之前),所有字段都处于初始(0或null)状态。 对于更复杂的值类型,它们的所有字段都处于初始(0或null)状态,以此类推。
它不会破坏应用程序,属性将具有其默认值-对象和字符串将设置为null
,布尔值设置为false
,整数/浮点数/双精度数为0
,字符为'\\0'
等。
如果您访问未设置的对象属性而不检查它们是否为null,则可能只会遇到null引用异常。
如果GetEmpInfo()
没有返回值,则emp
仍为null。 因此,当您调用emp
的属性(在您的情况下为字段)时,例如,当您调用emp.ID=100
,将获得System.NullReferenceException
(对象引用未设置为对象的实例) 。 您可以在代码中添加一个空检查:
Employee emp= pp.GetEmpInfo();
//pp is an instance of webservices which is web referenced in the app.
if (emp == null)
{
//you might choose to throw an error or set it to a new
//instance of an object.
emp = new Employee();
}
emp.ID=100;
emp.Age=25;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.