Ram*_*ujo 2 extension-methods c#-4.0
我只是想编写以下扩展方法:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我的意思是,我可以使用扩展方法来改变扩展类的值吗?我不想将void返回类型更改为int,只是更改扩展类值.提前致谢
您的示例使用int,这是一种值类型.类是引用类型,在这种情况下行为略有不同.
虽然您可以创建一个采用其他引用AssignMe(this MyClass me, MyClass other)的方法,但该方法将对引用的副本起作用,因此如果分配other给me它只会影响引用的本地副本.
另外,请记住,扩展方法只是伪装的静态方法.即他们只能访问扩展类型的公共成员.
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;
}
}
Run Code Online (Sandbox Code Playgroud)