我只是想编写以下扩展方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _4Testing
{
static class ExtensionMethods
{
public static void AssignMe(this int me, int value)
{
me = value;
}
}
}
但它不起作用,我的意思是,我可以使用扩展方法来更改扩展类中的值吗?我不想将 void 返回类型更改为 int,只是更改扩展类值。提前致谢
最佳答案
您的示例使用 int
,它是一种值类型。类是引用类型,在这种情况下,其行为略有不同。
虽然您可以创建一个采用另一个引用的方法,例如 AssignMe(this MyClass me, MyClass other)
,但该方法将在引用的副本上工作,因此如果您分配 other
到 me
它只会影响引用的本地副本。
此外,请记住扩展方法只是伪装的静态方法。 IE。他们只能访问扩展类型的公共(public)成员。
public sealed class Foo {
public int PublicValue;
private int PrivateValue;
}
public static class FooExtensions {
public static void Bar(this Foo f) {
f.PublicValue = 42;
// Doesn't compile as the extension method doesn't have access to Foo's internals
f.PrivateValue = 42;
}
}
关于c#-4.0 - 扩展方法可以修改扩展类值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3750407/