在C#中使用扩展方法更改值(如VB.NET所允许) [英] Change value using Extension Method in C# (as allowed in VB.NET)

查看:240
本文介绍了在C#中使用扩展方法更改值(如VB.NET所允许)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作

string s = "Hello";
s.Clear();

我创建了这样的扩展方法:

And I created the extension method like this:

public static void Clear(this string s)
{
    s = string.Empty;
}

但是,当我看到该值时,它并没有改变:

But, when I see the value, it does not change:

我不能使用 ref out ,因为它们不能与关键字 this 一起使用.有什么想法吗?

I can't use ref or out because these can't be used with the keyword this. Any ideas?

推荐答案

这是不可能的. 从文档:

字符串是不可变的-创建字符串对象后,其内容无法更改,尽管语法使它看起来好像可以执行此操作.例如,当您编写此代码时,编译器实际上会创建一个新的字符串对象来保存新的字符序列,并将该新对象分配给b.这样,字符串"h"就可以进行垃圾回收了.

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

这篇关于在C#中使用扩展方法更改值(如VB.NET所允许)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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