在.NET中字符串得到改变?有一些bug? [英] is strings in .net get changed?? is there some bug?

查看:116
本文介绍了在.NET中字符串得到改变?有一些bug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数反向扭转使用指针在不安全的情况下在.net中的字符串。 我不喜欢这样。

我分配问候和x相同的值。 我反问候让我吃惊的X还得到逆转。

 使用系统;

Test类{

    私人不安全静态无效反向(字符串文本){
        固定(字符* PSTR =文本){
            字符* pBegin = PSTR;
            字符*小彭= PSTR + text.Length  -  1;
            而(pBegin<小彭){
                烧焦T = * pBegin;
                * pBegin ++ = *小彭;
                * pEnd-- = T;
            }
        }
    }

    公共静态无效的主要(){
        串迎接=Hello World的;
        字符串x =Hello World的;
        反向(迎接);
        Console.WriteLine(迎接);
        Console.WriteLine(X);
    }
}
 

解决方案

没什么奇怪有关。你看到的实习的。如果你写的:

  Console.WriteLine(object.ReferenceEquals(打招呼,X));
 

在声明后,你会发现,你只得到的字符串对象的。无论你的变量指向同一个对象,所以很明显,如果你通过一个变量进行修改的对象,你会看到同样的变化,当您通过另一个变量稍后访问它。

从C#4规范,部分2.4.4.5:

  

每个字符串不一定产生新的字符串实例。当两个或多个字符串根据字符串相等运算符是等效的出现在同一程序中,这些字符串引用相同的字符串实例。

呵呵,我希望在现实code你没有的实际上的使用不安全的操作修改字符串...

I have written a function Reverse to reverse a string in .net using pointers in unsafe context. I do like this.

I allocate "greet" and "x" same value. I reverse greet to my surprise x also gets reversed.

using System;

class Test{

    private unsafe static void Reverse(string text){
        fixed(char* pStr = text){
            char* pBegin = pStr;
            char* pEnd = pStr + text.Length - 1;
            while(pBegin < pEnd){
                char t = *pBegin;
                *pBegin++ = *pEnd;
                *pEnd-- = t; 
            }
        }
    }

    public static void Main(){
        string greet = "Hello World";
        string x = "Hello World";
        Reverse(greet);
        Console.WriteLine(greet);
        Console.WriteLine(x);
    }
}

解决方案

Nothing odd about that. You're seeing interning. If you write:

Console.WriteLine(object.ReferenceEquals(greet, x));

immediately after the declaration, you'll see that you've only got one string object. Both your variables refer to the same object, so obviously if you make a modification to the object via one variable, you'll see the same change when you access it later through the other variable.

From the C# 4 spec, section 2.4.4.5:

Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator appear in the same program, these string literals refer to the same string instance.

Oh, and I hope that in real code you're not actually modifying strings using unsafe operations...

这篇关于在.NET中字符串得到改变?有一些bug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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