似乎C#中的扩展方法无法覆盖原始对象。这是为什么?例如:
using System;
namespace ExtensionTest
{
public class MyTest {
public string MyName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var myTest = new MyTest() { MyName = "Arne" };
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Arne"
myTest.AlterMyTest();
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Bertil"
myTest.OverwriteMyTest();
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Bertil" (why?)
}
}
public static class ExtensionClass{
public static void AlterMyTest(this MyTest myTest)
{
myTest.MyName = "Bertil";
}
public static void OverwriteMyTest(this MyTest myTest)
{
myTest = new MyTest() { MyName = "Carl" };
}
}
}
答案 0 :(得分:5)
因为像往常一样,在传递给方法时会复制类的引用,并且您要将新对象分配给新引用。
对于非扩展方法,您可以通过ref/out
关键字
public static void Func(out MyClass b)
{
b = new MyClass();
}
...
MyClass b;
Func(out b);
Assert.IsNotNull(b);
但是C#编译器不允许ref
与this
一起使用(原因在于David Arno的评论)。您可以自由删除this
关键字,并调用静态方法而不是扩展名。