1

次のコードを見てください。

static void Main(string[] args)
{
    string s = null;
    string[] myArray = new string[1];

    { } // do something evil here

    if (s.GetType() == typeof(int))
    {
        Console.WriteLine("This should not happen!"); 
    }
    Console.ReadLine();
}

This should not happen書けるようになる方法はありますか?そうではないと思います。ただし、デバッガーを使用して行うことができます。行にブレークポイントを配置し、{ } // do something evil here続行する前にイミディエイト ウィンドウで次のコマンドを実行します。

((object[])myArray)[0] = 99;
s = myArray[0];

実行は続行され、This should not happen出力されます。Visual Studio 2008 でテスト済み。ここにスクリーンショットがあります:

スクリーンショット

この種のトリッキーはデバッガでのみ可能ですか、それともコードでそのような「安全でない割り当て」を行う方法はありますか?

(明らかに、私は科学的な好奇心からのみ尋ねます。この質問と関連するコメントが、私にこの質問をさせました。)

4

1 に答える 1

2

1 つの手法はLayoutKind.Explicit、任意のオブジェクトを文字列に再解釈するために使用できる共用体を実装するために使用します。最初に int をボックス化し、それを共用体のフィールドに割り当ててからobject、文字列フィールドを読み取ります。

[StructLayout(LayoutKind.Explicit)]
public struct Evil
{
    [FieldOffset(0)]
    public string s;

    [FieldOffset(0)]
    public object o;
}

string ReinterpretCastToString(object o)
{
    Evil evil=new Evil();
    evil.o=o;
    return evil.s;
}

void Main()
{
    string s = ReinterpretCastToString(1);

    if (s.GetType() == typeof(int))
    {
        Console.WriteLine("This should not happen!"); 
    }
}

これは、いつでも機能しなくなる可能性のある未定義の動作である可能性が最も高いです。明らかに、これを実際のプログラムで使用するべきではありません。

于 2013-07-14T20:52:22.277 に答える