简体   繁体   English

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

[英]C# call by value/ref + extension methods

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);
}

Output: 输出:

1: 0; 1:0; 0 0

2: 0; 2:0; 0 0

3: 50; 3:50; 50 50

What I expected: 我的期望:

1: 0; 1:0; 0 0

2: 50; 2:50; 50 50

why does rect.Offseted(50, 50) not modify the x and y of the rectangle in step 2? 为什么rect.Offseted(50,50)不会在步骤2中修改矩形的x和y?

What do I have to do with my RectangleExtension method to get my expected result? 我如何处理RectangleExtension方法以获得预期的结果?

The answer is: structs are always passed by value in C#, and Rectangle in your case is a struct , not a class . 答案是: structs总是在C#中通过值传递,而在你的情况下,Rectangle是一个struct ,而不是一个class

Try this: 尝试这个:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM