我们可以拥有通用属性吗?我需要存储数据。所以我已经使用Generic Properties进行了类。当我将数据添加到该属性时出现错误“对象引用未设置为实例一个对象“。请给我一些想法。
class GeneralClass { private List<int> _student_rollnumber; public List<string> _student_name; public List<int> Student_RollNumber { get { return _student_rollnumber; } set { _student_rollnumber = value; } } public List<string> Student_Name { get { return _student_name; } set { _student_name = value; } } }
我在Button Click中使用了Class。
private void btn_save_Click(object sender, EventArgs e) { try { GeneralClass obj = new GeneralClass(); obj.Student_RollNumber.Add(int.Parse(txtbx_rollnum.Text)); obj.Student_Name.Add(txtbx_SName.Text); MessageBox.Show("Data saved"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message from form"); } }
答案 0 :(得分:0)
这与泛型无关。
您只是没有初始化您的成员变量,即_student_rollnumber
和_student_name
,因此当您尝试null
值时,它们为Add
。
答案 1 :(得分:0)
您没有初始化列表,因此它们默认为null
,这意味着当您尝试在点击处理程序方法中添加NullReferenceException
时,会得到class GeneralClass
{
// initialise to a new List<int>, otherwise it will default to null
private List<int> _student_rollnumber = new List<int>();
// initialise to a new List<string>, otherwise it will default to null
private List<string> _student_name = new List<string>();
public List<int> Student_RollNumber
{
get { return _student_rollnumber; }
// chances are that you don't need the setter, uncomment it if you do
//set { _student_rollnumber = value; }
}
public List<string> Student_Name
{
get { return _student_name; }
// chances are that you don't need the setter, uncomment it if you do
//set { _student_name = value; }
}
}
。
{{1}}
答案 2 :(得分:0)
class GeneralClass
{
public GeneralClass
{
_student_rollnumber = new List<int>();
_student_name = new List<string>();
}
private List<int> _student_rollnumber;
public List<string> _student_name;
public List<int> Student_RollNumber
{
get { return _student_rollnumber; }
set { _student_rollnumber = value; }
}
public List<string> Student_Name
{
get { return _student_name; }
set { _student_name = value; }
}
}
答案 3 :(得分:0)