1

デバッグ中に、null 参照があるというエラーでプログラムがクラッシュしました。奇妙なことは、クラッシュした行で、別の静的クラスでメソッドを実行していて、パラメーターの 1 つが「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>();
        }
    }
4

1 に答える 1

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 が原因でアプリがクラッシュした理由については、その例外がスローされた場所に関するスタック トレースがある場合にのみ回答できます。

于 2013-06-10T05:50:10.963 に答える