Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 存在值时,asp.net null引用将值分配给对象时出错_C#_Asp.net - Fatal编程技术网

C# 存在值时,asp.net null引用将值分配给对象时出错

C# 存在值时,asp.net null引用将值分配给对象时出错,c#,asp.net,C#,Asp.net,我有一个使用强类型对象的搜索页面,但是我将这些值分成了特定的组 当用户单击“搜索”按钮时,“代码隐藏”页面调用以下内容(这些字段均为空): 数据类型文件的定义如下: [Serializable] public class SearchCriteria { public _Generic Generic { get;set; } [Serializable] public class _Generic { public int id {get;s

我有一个使用强类型对象的搜索页面,但是我将这些值分成了特定的组

当用户单击“搜索”按钮时,“代码隐藏”页面调用以下内容(这些字段均为空):

数据类型文件的定义如下:

[Serializable]
public class SearchCriteria 
{
    public _Generic Generic { get;set; }
    [Serializable]
    public class _Generic 
    {
        public int id {get;set;}
        public int maxReturned {get;set;}
    }

    public _DisplayOnly DisplayOnly { get;set; }
    [Serializable]
    public class _DisplayOnly 
    {
        public int category {get;set;}
        public int type {get;set;}
    }

    public _Building Building { get;set; }
    [Serializable]
    public class _Building 
    {
        public int address {get;set;}
        public int city {get;set;}
    }
}

当代码执行时,我得到一个nullreferenceerror,即使各种文本框中的所有项都有一个值。但是,如果我取出public _Building{get;set;}并直接调用该类,它就会工作并填充值。这里最好的解决方案是什么?我是否应该使用中介定义并直接调用类?如果是这样,我如何调用不同的组而不在代码隐藏页上进行四次不同的调用?

您需要初始化内部类实例。简单地声明变量并不意味着不创建实例就可以访问它们的属性。您可以在
SearchCriteria
类的构造函数中轻松实现这一点

[Serializable]
public class SearchCriteria 
{
    public SearchCriteria()
    {
         // Without these initialization the internal variables are all null
         // and so assigning any property of a null object causes the error
         Generic = new _Generic();
         DisplayOnly = new _DisplayOnly()
         Building = new _Building();
    }
    .....
}

创建
SearchCriteria
类的新实例时,属性未初始化,因此它们的值均为
null
。现在来看第一行,您尝试使用其中一个属性:

sc.Generic.id = txtId.Text;
这里,
txtID.Text
非常好,但是
sc.Generic
null
。当您尝试查找分配的it's
.id
属性时,会在那里引发异常

要解决此问题,您需要初始化这些属性中的每一个,以获得其类型的实例。此外,使用私有集可能是个好主意,如下所示:

public _Generic Generic { get;private set; }
这仍然允许进行当前编写的所有相同的赋值,因为这只需要
get
操作来检索类型实例。赋值/设置操作在属性的属性上

public _Generic Generic { get;private set; }