简体   繁体   English

具有属性但未分配属性的类

[英]Class with properties but few properties not assigned

I have c# class i have different properties. 我有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;

I don't assign/get return value for name from GetEmpInfo() , will that throw any exception? 我不从GetEmpInfo()分配/获取名称的返回值,这会引发任何异常吗?

If you have a class with 10 properties and don't assign few, will it break the application? 如果您有一个包含10个属性的类,却没有分配几个属性,那么它将破坏应用程序吗?

Please share your thoughts. 请分享您的想法。 There is some code in production, i am not sure of the result, so am checking. 生产中有一些代码,我不确定结果如何,因此请检查。

If your web service method returns null : 如果您的Web服务方法返回null

[WebMethod]
public Employee GetEmpInfo()
{
    return null;
}

then the following will throw a NullReferenceException : 然后以下将引发NullReferenceException

emp.ID = 100;

because the emp variable won't be assigned. 因为不会分配emp变量。

In order to avoid this verify if the variable has been assigned before accessing its properties (or in your case public fields): 为了避免这种情况,请在访问变量的属性(或在您的情况下为公共字段)之前验证是否已分配变量:

Employee emp = pp.GetEmpInfo(); 
if (emp != null)
{
    emp.ID = 100;
    emp.Age = 25;
}

After initial construction (before constructor is called), all fields are in initial (0 or null) state. 初始构造之后(在调用构造函数之前),所有字段都处于初始(0或null)状态。 For more complex value types, all of their fields are in initial (0 or null) state and so on, recursively. 对于更复杂的值类型,它们的所有字段都处于初始(0或null)状态,以此类推。

It will not break the application, the attributes will have their default value - objects and strings will be set to null , booleans to false , integers/floats/doubles to 0 , chars to '\\0' etc. 它不会破坏应用程序,属性将具有其默认值-对象和字符串将设置为null ,布尔值设置为false ,整数/浮点数/双精度数为0 ,字符为'\\0'等。
You only might encounter null reference exceptions if you access object attributes that have not been set without checking them for null. 如果您访问未设置的对象属性而不检查它们是否为null,则可能只会遇到null引用异常。

If GetEmpInfo() does not return a value, emp will still be null. 如果GetEmpInfo()没有返回值,则emp仍为null。 Thus when you go to call a property (or in your case, a field) of emp , such as when you call emp.ID=100 , you will get a System.NullReferenceException (Object reference not set to an instance of an object). 因此,当您调用emp的属性(在您的情况下为字段)时,例如,当您调用emp.ID=100 ,将获得System.NullReferenceException (对象引用未设置为对象的实例) 。 You might add a null check to your code: 您可以在代码中添加一个空检查:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM