我是 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/