C# 如何在c中为字符串添加扩展方法#

C# 如何在c中为字符串添加扩展方法#,c#,string,extension-methods,C#,String,Extension Methods,如果我有字符串:string a=“你好” 我希望我能做到:a.replacetresubstring() 期待a=“你好” 我试着这样做: public static class ChangeString { public static string ReplaceThereSubstring(this String myString) { return myString.Replace("there","here");

如果我有字符串:
string a=“你好”

我希望我能做到:
a.replacetresubstring()

期待
a=“你好”

我试着这样做:

public static class ChangeString
    {
        public static string ReplaceThereSubstring(this String myString)
        {
           return myString.Replace("there","here");
        }
    }

但是它总是返回null。

在这种情况下,您应该这样做来运行代码:

string a = "Hello there"
a = a.ReplaceThereSubstring();

您不能在扩展方法中替换字符串的值,因为字符串是不可变的。在这种情况下,您应该这样做来运行代码:

string a = "Hello there"
a = a.ReplaceThereSubstring();

您不能在扩展方法中替换字符串的值,因为字符串是不可变的,当然,您需要分配结果:

string b = a.ReplaceThereSubString();

当然,您需要指定结果:

string b = a.ReplaceThereSubString();

无法修改现有字符串,因为

所以像
myString.Replace(“there”,“here”)
不会更改myString实例

您的扩展方法实际上是正确的,但您应该这样使用它:

a = a.ReplaceThereSubstring();

无法修改现有字符串,因为

所以像
myString.Replace(“there”,“here”)
不会更改myString实例

您的扩展方法实际上是正确的,但您应该这样使用它:

a = a.ReplaceThereSubstring();

不,该代码不会返回null。请展示一个简短但完整的程序来演示这个问题。我编辑了它。但是我刚刚看到字符串类是不可变的。我不知道我是否可以做到。你必须重新分配它<代码>变量a=a.ReplaceThereSubstring()@jeroenvanevel
var
真的应该存在吗?这将通过引用
a
来定义
a
,不是吗?@ThorstenDittmar:是的,它应该被删除或者有一个不同的名称。没有太注意它,因为它是用来演示重新分配的。不,该代码不会返回null。请展示一个简短但完整的程序来演示这个问题。我编辑了它。但是我刚刚看到字符串类是不可变的。我不知道我是否可以做到。你必须重新分配它<代码>变量a=a.ReplaceThereSubstring()@jeroenvanevel
var
真的应该存在吗?这将通过引用
a
来定义
a
,不是吗?@ThorstenDittmar:是的,它应该被删除或者有一个不同的名称。没有太注意它,因为它是为了证明重新分配。