绕过C#的类型保障和在字符串存储一个整数 [英] Bypassing C#'s type safeguards and storing an Integer in a String

查看:121
本文介绍了绕过C#的类型保障和在字符串存储一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看一看下面的代码:

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();
}



有没有什么办法让这不应该发生写?人们会认为不会。但是,它可以使用调试器来完成:将一个断点入行 {} //做邪恶的东西在这里并执行在立即窗口下面的命令,然后再继续:

Is there any way to get This should not happen to write? One would assume not. However, it can be done with the debugger: Put a breakpoint into the line { } // do something evil here and execute the following commands in the Immediate Window before continuing:

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



继续执行与这不应该发生将被打印。与Visual Studio 2008进行测试;这里是截图:

Execution continues and This should not happen will be printed. Tested with Visual Studio 2008; here is a screenshot:

这是一种欺骗的只能用调试器可能的,或者是有一些方法的代码做这样一个不安全赋值?

Is this kind of trickery only possible with the debugger or is there some way to do such an "unsafe assignment" in code?

(显然,我问只是出于科学好奇心。这个问题和相关评论让我问这个问题。 )

(Obviously, I ask only out of scientific curiosity. This question and the related comments made me ask this question.)

推荐答案

一种方法是使用 LayoutKind.Explicit 实施工会它可以用来重新诠释投一个任意对象的字符串。第一个框一个int,然后将其分配给对象工会字段,然后读出字​​符串字段。

One technique is using LayoutKind.Explicit to implement a union which can be used to reinterpret cast an arbitrary object to string. First box an int, then assign it to the object field of the union and then read out the string field.

[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!"); 
    }
}

这是最有可能的不确定的行为,可能会停止工作任何时候。显然,你不应该在实际的程序中使用此功能。

This is most likely undefined behavior that may stop working at any time. Obviously you shouldn't use this in a real program.

这篇关于绕过C#的类型保障和在字符串存储一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆