字符串变量自动更改为“null”

时间:2013-05-22 11:58:02

标签: c# .net reflection

我遇到了一些奇怪的东西,我创建了一个带有反射的类的实例,这传递了几个参数,一个是变量:ipAddress,当在构造函数中创建实例时,变量存储在一个字段中,但是一旦构造函数完成并且我(在调试器中)返回到我创建实例的行,我在类中检查并且字段'ipAddress'已经更改为null。这怎么可能?

这是课程的一部分:

public class moxa_nport_5110
{
    string instanceName;
    Delegate triggerCallBackMethod;

    private BPUConsole bpuConsole { get; set; }

    TcpIpServer server;
    string ipAddress;

    public moxa_nport_5110(Delegate TriggerCallBackMethod, Delegate Callback, params object[] CtorParam)
    {
        #region Initialize
        triggerCallBackMethod = TriggerCallBackMethod;
        instanceName = (string)CtorParam[0];
        string ipAddress = (string)CtorParam[1];
        int Port = (int)CtorParam[2];
        bpuConsole = new BPUConsole(Callback, instanceName);
        #endregion

        server = new TcpIpServer("10.100.184.140", 8888, false);
        server.OnDataReceived += new TcpIpServer.ReceiveEventHandler(server_OnDataReceived);
        server.OnClientConnected += new TcpIpServer.InfoEventHandler(server_OnClientConnected);
        server.OnClientDisconnected += new TcpIpServer.InfoEventHandler(server_OnClientDisconnected);
        server.OnAbnormalConnectionDisconnect += new TcpIpServer.InfoEventHandler(server_OnAbnormalConnectionDisconnect);
        server.AddClient(ipAddress, 1);
    }

    public void SendData(byte[] Data)
    {
        server.SendData(ipAddress, Data);
    }

这是我创建实例的行:

driverInterface = Activator.CreateInstance(driverType, tempParam);  //create an instance of the driver

所以当我返回这里时,字段ipAddress的值为null。

编辑:

字段是相同的值但未加入:

enter image description here

2 个答案:

答案 0 :(得分:6)

string ipAddress;

public moxa_nport_5110(Delegate TriggerCallBackMethod, Delegate Callback, params object[] CtorParam)
{
    #region Initialize
    triggerCallBackMethod = TriggerCallBackMethod;
    instanceName = (string)CtorParam[0];
    string ipAddress = (string)CtorParam[1];
}

String是类的一个字段,因此您需要使用this.设置该值。您只是创建一个名为ipAdress的“新”字符串,它会遮挡该字段。在构造函数中使用this.ipAdress = ...

答案 1 :(得分:3)

在这种情况下,你有两个同名的变量,第二个因上下文而优先:string ipAddress = (string)CtorParam[1];设置变量,但也创建一个独特的变量 - 持续“方法的“生命周期”(构造函数,这里) - 与前一个具有相同名称的声明完全无关。

要设置更高级别的变量,请从语句中删除类型前缀:

ipAddress = (string)CtorParam[1];