我正在尝试创建事件,但出现 NullReferenceException
I'm trying to create an event but I get a NullReferenceException
我想在 C# 中创建一个事件,但出现此错误:
An unhandled exception of type 'System.NullReferenceException' occurred in shei graii.exe
Additional information: Object reference not set to an instance of an object.
服务器代码:
public class mobile
{
public delegate void chargeEvent();
public event chargeEvent sampleEvent;
private byte _charge;
public byte charge
{
set
{
_charge = value;
if (_charge <= 15)
{
sampleEvent(); // the error line
}
}
}
}
客户代码:
mobile mob = new mobile();
mob.charge = 14;
mob.sampleEvent += new mobile.chargeEvent(input);
输入密码:
public void input()
{
MessageBox.Show("battery low");
}
您收到 NullReference
错误,因为您尝试在设置事件之前调用该事件。所以试试这个:
mobile mob = new mobile();
mob.sampleEvent += new mobile.chargeEvent(input);
mob.charge = 14;
我们只能使用您提供的有限代码。
我想在 C# 中创建一个事件,但出现此错误:
An unhandled exception of type 'System.NullReferenceException' occurred in shei graii.exe
Additional information: Object reference not set to an instance of an object.
服务器代码:
public class mobile
{
public delegate void chargeEvent();
public event chargeEvent sampleEvent;
private byte _charge;
public byte charge
{
set
{
_charge = value;
if (_charge <= 15)
{
sampleEvent(); // the error line
}
}
}
}
客户代码:
mobile mob = new mobile();
mob.charge = 14;
mob.sampleEvent += new mobile.chargeEvent(input);
输入密码:
public void input()
{
MessageBox.Show("battery low");
}
您收到 NullReference
错误,因为您尝试在设置事件之前调用该事件。所以试试这个:
mobile mob = new mobile();
mob.sampleEvent += new mobile.chargeEvent(input);
mob.charge = 14;
我们只能使用您提供的有限代码。