如何在 C# 中从另一个私有 class 调用私有 class 变量

how to call a private class variable form an other private class in C#

我的代码是如何从私有下面调用变量 startX class

如果在 C# 上有任何可能的方法从另一个私有 class

调用私有 class 变量

这可能是一个简单的问题,但我是初学者

你能帮帮我吗

    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        moving = true;
        x = e.X;
        y = e.Y;

        panel1.Cursor = Cursors.Cross;
        label1.Text = "" + e.X + "";
        label2.Text = "" + e.Y + "";
        int startX = e.X;
        int startY = e.Y;

    }

    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        moving = false;
        x = -1;
        y = -1;
        panel1.Cursor = Cursors.Default;
        int downy = e.X;
        label3.Text = "" + downy + "";
        string one = "1";

        //how to call int startX on this class




        if (label1.Text == label3.Text || label2.Text == label4.Text)
        {
            button1.Text = "The number is : " + one + "";
        }
        else
        { button1.Text = "The number can't calculat"; }
    }

panel1_MouseDown 不是 class,它是私有方法,您不调用变量,而是调用方法。如果你需要在 panel1_MouseUp 方法中使用 startX 的值,你可以给你的 panel1_MouseDown 方法一个 return 值,或者你创建一个全局变量来存储该值。由于您的方法是由鼠标事件调用的,因此我建议使用全局变量。

private int lastStartX = 0;

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    moving = true;
    x = e.X;
    y = e.Y;

    panel1.Cursor = Cursors.Cross;
    label1.Text = "" + e.X + "";
    label2.Text = "" + e.Y + "";
    int startX = lastStartX = e.X;
    int startY = e.Y;

}

private void panel1_MouseUp(object sender, MouseEventArgs e)
{
    moving = false;
    x = -1;
    y = -1;
    panel1.Cursor = Cursors.Default;
    int downy = e.X;
    label3.Text = "" + downy + "";
    string one = "1";

    //how to call int startX on this class
    //do whatever you want with lastStartX


    if (label1.Text == label3.Text || label2.Text == label4.Text)
    {
        button1.Text = "The number is : " + one + "";
    }
    else
    { button1.Text = "The number can't calculat"; }
}

简单的回答,你不能。

关于局部函数的一些文档:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions

您将在 class 而不是函数内创建一个变量。

public class Class
{
    private int startX;
    private int startY;

    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        this.startX = e.X;
        this.startY = e.Y;
    }
    
    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        // call this.startX or this.startY
    }
}