Method string.Replace( ) doesn't work

2019-02-27 13:08发布

问题:

    public string Generate()
    {
        RandomNumberGenerator rdng = new RNGCryptoServiceProvider();
        byte[] bytes = new byte[40];

        rdng.GetBytes(bytes);

        string a = Convert.ToBase64String(bytes); 

        a.Replace("=", "r");
        a.Replace("+", "t");

        return a;
    }

a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;

after a.Replace() again:

a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;

I want to generate unique value in my C# project. Everything is great. But When I want to call string.Replace(), it doesn't work. Values after and before this method are the same. Why ?

回答1:

The replace method returns a new string object, it does not modify the existing string. The following statement should work:

a = a.Replace("=", "r");


回答2:

It works. It just doesn't do what you think: it doesn't edit the existing string: it creates a new string. Try:

    a = a.Replace("=", "r");
    a = a.Replace("+", "t");

This is because strings are immutable: they do not change once created (at least, not if you might be looking - there are some exceptions like the internals of StringBuilder, but those are implementation details that you shouldn't see)



回答3:

The problem is that the method doesn't change the string you call the method on, but returns another occurrence of the string, so you should assign it to another object in order for the changes to persist because a string is a non mutable object:

a=a.Replace("=", "r");
a=a.Replace("+", "t");


回答4:

String.Replace is not modifying a, but returning a new String. As this makes it chainable, a solution could look like:

a = a.Replace("=", "r").Replace("+", "t");


标签: c# string random