在调试时,我的程序因错误声明存在空引用而崩溃。奇怪的是,在它崩溃的那一行上,它正在一个不同的静态类中运行一个方法,其中一个参数填充了“this”,这意味着它正在为正在进行调用的对象提供信息。当我将鼠标悬停在“this”上时,它不是调用对象,而是不同类类型的完全不同的对象。
有没有人知道或者有任何解释如何使用“this”可能使“this”成为与调用类甚至不同类型的对象?
这是有问题的方法。
public void UpdateLight()
{ DoUpdateLight(); }
protected virtual void DoUpdateLight()
{
if (isActive)
{
Systems.Lighting.Instance.SetSpotLight(
this,
(int)(owner.GetEyeHeight - owner.GetHeight * 0.25f),
lightRange,
owner.visionAngleHorizontal,
owner.visionAngleVertical,
owner.GetGridNumber,
owner.parentFloor.floorLevel,
lightStrength,
lightDecay,
lightMaxTiles,
800);
RemoveLights();
litObjectsPrev = litObjects;
litObjects = new List<ILightable>();
}
}
答案 0 :(得分:0)
回答你的问题:
有没有人知道或者有任何解释如何使用“this”可能使“this”成为与调用类甚至不同类型的对象?
是。 this
不一定是班级本身。这可能是因为继承。这意味着this
的类型实际上是它的孩子。
考虑在下面运行此代码段(控制台应用):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace thisSample
{
class Program
{
static void Main(string[] args)
{
BaseClass b = getClass("Child");
b.SayHelloAndMyType();
}
static BaseClass getClass(string name)
{
BaseClass returnValue = null;
switch (name)
{
case "Base":
returnValue = new BaseClass();
break;
case "Child":
returnValue = new ChildClass();
break;
default:
returnValue = new BaseClass();
break;
}
return returnValue;
}
}
class BaseClass
{
private const string NAME = "Base class";
public virtual string GetName()
{
return NAME;
}
public virtual void SayHelloAndMyType()
{
Console.WriteLine("Hello from " + this.GetName() + " and my type is " + this.GetType().ToString()); //this.GetName() could be "Base class" or not. Depending on what instance it really is "this" (Base or Child)
}
}
class ChildClass : BaseClass
{
private const string NAME = "Child class";
public override string GetName()
{
return NAME;
}
}
}
现在,为什么你的应用程序因为NullReferenceException而崩溃,只有在有关于抛出异常的位置的堆栈跟踪时才能回答它。