C#按值/ ref +扩展方法调用

时间:2014-03-30 18:52:05

标签: c# winforms

public static class RectangleExtension
{
    public static Rectangle Offseted(this Rectangle rect, int x, int y)
    {
        rect.X += x;
        rect.Y += y;
        return rect;
    }
}


....

public void foo()
{
    Rectangle rect;

    rect = new Rectangle(0, 0, 20, 20);
    Console.WriteLine("1: " + rect.X + "; " + rect.Y);

    rect.Offseted(50, 50);  
    Console.WriteLine("2: " + rect.X + "; " + rect.Y);

    rect = rect.Offseted(50, 50); 
    Console.WriteLine("3: " + rect.X + "; " + rect.Y);
}

输出:

1:0; 0

2:0; 0

3:50; 50

我的期望:

1:0; 0

2:50; 50

为什么rect.Offseted(50,50)不会在步骤2中修改矩形的x和y?

我如何处理RectangleExtension方法以获得预期的结果?

1 个答案:

答案 0 :(得分:2)

答案是:structs始终按C#中的值传递,而案例中的矩形是struct,而不是class

试试这个:

public class A {
    public int x;
}
public struct B {
    public int x;
}
public static class Extension {
    public static A Add(this A value) {
        value.x += 1;
        return value;
    }
    public static B Add(this B value) {
        value.x += 1;
        return value;
    }
}
class Program {
    static void Main(string[] args) {
        A a = new A();
        B b = new B();
        Console.WriteLine("a=" + a.x);
        Console.WriteLine("b=" + b.x);
        a.Add();
        b.Add();
        Console.WriteLine("a=" + a.x); //a=1
        Console.WriteLine("b=" + b.x); //b=0
        Console.ReadLine();
    }
}