我试图以不同的方式初始化构造函数,如果它使用符合特定条件的参数调用,并且我有以下代码.
class MessageEventArgs : EventArgs
{
private int _pId;
private string _message;
private string _channelPath;
public MessageEventArgs(string message)
{
_pId = Process.GetCurrentProcess().Id;
_message = message;
_channelPath = null;
}
public MessageEventArgs(string[] details)
{
if (details.Length == 1)
{
new MessageEventArgs(details[0]);
return;
}
_pId = int.Parse(details[0]);
_message = details[1];
_channelPath = details[2];
}
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,在逐行调试和逐步调试时,我看到所有调用都正常,但在实例化之后,pId
并且_message
具有默认值,即0和null
您没有调用其他构造函数,而是创建了使用默认值初始化的第二个实例.
因此,第一个实例仍未初始化.
你需要这样做:
class MessageEventArgs : EventArgs
{
private int _pId;
private string _message;
private string _channelPath;
public MessageEventArgs(string message)
{
_pId = Process.GetCurrentProcess().Id;
_message = message;
_channelPath = null;
}
public MessageEventArgs(string[] details)
{
if (details.Length == 1)
{
_pId = Process.GetCurrentProcess().Id;
_message = details[0];
_channelPath = null;
return;
}
_pId = int.Parse(details[0]);
_message = details[1];
_channelPath = details[2];
}
}
Run Code Online (Sandbox Code Playgroud)
我可能会检查细节是否null
也是..
按照规范,在C#中,你不能从类中调用另一个构造函数.所以它不是return语句,而是调用其他构造函数的不正当尝试.你必须制作一个Initialize
方法来体现你想要做的事情并从两种方法中调用它.
class MessageEventArgs : EventArgs
{
private int _pId;
private string _message;
private string _channelPath;
public MessageEventArgs(string message)
{
Initialize( message );
}
public MessageEventArgs(string[] details)
{
if (details.Length == 1)
{
Initialize( details[ 0 ] );
return;
}
_pId = int.Parse(details[0]);
_message = details[1];
_channelPath = details[2];
}
private void Initialize(string message)
{
_pId = Process.GetCurrentProcess().Id;
_message = message;
_channelPath = null;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1969 次 |
最近记录: |