要改变这样的字符串的内容导致异常? [英] Should changing the contents of a string like this cause an exception?
本文介绍了要改变这样的字符串的内容导致异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑下面的代码:
using System;
using System.Runtime.InteropServices;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
const string test = "ABCDEF"; // Strings are immutable, right?
char[] chars = new StringToChar{str=test}.chr;
chars[0] = 'X';
// On an x32 release or debug build or on an x64 debug build,
// the following prints "XBCDEF".
// On an x64 release build, it prints "ABXDEF".
// In both cases, we have changed the contents of 'test' without using
// any 'unsafe' code...
Console.WriteLine(test);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
[FieldOffset(0)]
public string str;
[FieldOffset(0)]
public char[] chr;
}
}
通过运行这段代码,我们能够改变字符串的内容没有例外发生的历史。我们没有宣布任何不安全的代码,这样做。 !这段代码显然是非常不可靠的。
By running this code, we are able to change the contents of a string without an exception occuring. We did not have to declare any unsafe code to do so. This code is clearly very dodgy!
我的问题很简单:你认为异常应通过上面的代码
My question is simply this: Do you think that an exception should be thrown by the code above?
推荐答案
我的投票对决策FieldOffset不安全。
My vote's on making FieldOffset unsafe.
这篇关于要改变这样的字符串的内容导致异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文