2014-03-30 68 views
3
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); 
} 

输出:C#呼叫

1:0; 0

2:0; 0

3:50; 50

我的预期:

1:0; 0

2:50; 50

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

我需要用我的RectangleExtension方法来获得预期的结果?

+0

(参照RECT).Offseted(50,50); –

回答

2

答案是:structs总是按C#中的值传递,而您的情况中的Rectangle是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(); 
    } 
} 
+0

谢谢!我不知道矩形是一个结构... – Felix

+1

这只是一个例子,为什么很多人说[可变结构是邪恶的](http://stackoverflow.com/questions/441309/why-are-mutable-structs-邪恶)。这与延伸方法无关。通常的方法会发生同样的情况,其中'rect'是一个值参数。类型['System.Drawing.Rectangle'](http://msdn.microsoft.com/en-us/library/system.drawing.rectangle.aspx)被设计为一个邪恶的结构(对于.NET 1.0)。也可以尝试'list [0] .Offset(50,50);''Offset'是'Rectangle'中的实例方法(BCL附带),'list'是'List '。 'List <>'有一个索引器。 –