簡體   English   中英

C#委托給struct方法

[英]C# delegate to struct method

我正在嘗試為特定實例的struct方法創建委托。 但是,事實證明,創建了一個新的struct實例,當我調用該委托時,它會在新創建的實例而不是原始實例上執行該方法。


static void Main(string[] args)
{
Point A = new Point() { x = 0 };
Action move = A.MoveRight;
move();
//A.x is still zero!
}

struct Point { public int x, y; public void MoveRight() { x++; } }

實際上,在這個例子中發生的是在委托創建者上創建一個新的struct Point實例,並且在通過delagate調用時對該方法執行該方法。

如果我使用類而不是結構,問題就解決了,但我想使用結構。 我也知道有一個解決方案,創建一個開放的委托,並將結構作為第一個參數傳遞給委托,但這個解決方案似乎相當沉重。 這個問題有什么簡單的解決方案嗎?

不,沒有辦法解決這個問題。 你有特定的理由使用struct嗎? 除非你特別需要它,否則你真的應該使用class

順便說一句,你已經創建了一個可變結構(一個可以改變其值的結構),這可以毫不誇張地說是詛咒。 你需要使用一個班級。

可變結構是邪惡的,不應該使用!*

您可以將struct更改為不可變,並使用MovePoint方法返回結構的新值:

struct Point {
    private readonly int x, y;
    public Point(x, y) { 
        this.x = x; this.y = y;
    }

    public struct MoveRight() {
        x++;
    }
}

然后你使用Func<Point, Point>來表示改變點的操作:

Func<Point, Point> move = a => a.MoveRight;

Point A = new Point() { x = 0 };
Point newA = move(A);
// newA.x is 1, but A.x is still 0, because struct is immutable
Point anotherA = move(newA);
// move the point again...

*) 當然,有些情況下它們可能有用,但如果你的情況是其中之一,你就不會問這個問題。

Anathema或不在辦公室使用C#。 在3D引擎中,我們做任何惡魔工作。 因此,例如在Unity3D引擎中,Vector3是struct,你有函數Set(x,y,z),你甚至可以改變x,y,z,因為它們是公共字段。 一切都是為了速度(例如,如果你對此計算較少,你將擁有其他東西。

  static void Main(string[] args)
    {
    Point A = new Point() { x = 0 };
    MyPointDelegate<Point> move=(ref Point p)=> p.MoveRight();
    move(ref A);
    Console.Write(A.x);
    //A.x is one!
    }



public delegate void MyPointDelegate<Point>(ref Point t);

struct Point
{
    public int x, y;

    public void MoveRight()
    {
        x++;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM