c# - 是什么导致我的构造函数中的 "this"指针为空?

标签 c# reference null this

我是 c# 的新手,将它与 unity3D 一起使用。当我使用 new 关键字初始化一个对象时,它似乎包含 null,即使该对象已创建并且构造函数已执行:

public class Wire
{
  public Wire()
  { 
    System.Console.WriteLine("constructor executed");
    System.Console.WriteLine(this);
  }
}

Wire wire1 =new Wire();
System.Console.WriteLine(wire1);

输出是:

constructor executed
null
null

我需要将引用存储在列表中,但现在不能。我该如何解决这个问题?


好的实际代码是

public class SharedResources
{    
    public static Dictionary< GameObject , Wire> dict = 
       new Dictionary<GameObject, Wire>();
    //...
}

public class Wire
{
    public GameObject x = y.y; 
    //y.y is another gameobject so its a normal copy constructer

    public Wire()
    { 
        print("constructor executed"); 
        // print is provided from unity package
        SharedResources.dict.Add( x,this);
    }
}

主要是我有

Wire wire1 = new Wire();
if ( SharedResources.dict.ContainsKey( wire1.x) )
{
    print("ok"); // it does print that!!
    if ( SharedResources.dict[wire1.x] !=null )
        print("its not null");
    else
        print("its null");
}

输出:

constructor executed
ok
its null

最佳答案

那是不可能的。

this 关键字永远不能是 null 引用,构造函数永远不能返回 null 引用,并且调用 Console.WriteLine null 引用不显示“null”,它显示一个空行,即与 Console.WriteLine(String.Empty) 相同。

如果重写 ToString 方法以返回字符串 "null",则可以获得该行为:

public class Wire {

  public Wire() {
    System.Console.WriteLine("constructor executed");
    System.Console.WriteLine(this);
  }

  public override string ToString() {
    return "null";
  }

}

关于c# - 是什么导致我的构造函数中的 "this"指针为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402210/

相关文章:

c# - 从 MD5 散列而不是字符串创建 Guid 是否有效?

c# - 使用 Mock 对 void 方法进行单元测试?

c# - 为什么是??运算符(operator)不在最小起订量设置方法中工作

http - $http 每次启动后( ionic )在第一次调用时返回错误响应 NULL,但在随后的 http 发布后就可以了

null - EasyMock andReturn() 空返回值

c# - 我不认为我正在修改这个集合

c# - 如何以编程方式在 IIS 7 中获取站点列表和虚拟目录?

c++ - 尝试通过 .h 和 .cpp 文件设置类——为什么会出现这些错误?

c++ - 在这种情况下,可以避免在c++中手动管理内存吗?

c++ - 这样安全吗?右值和引用返回值