如何在方法之外访问 'var' 类型的变量?

How to access variable of type 'var' outside of method?

我正在尝试访问存储在方法变量中的值 var pitch,但我不确定如何从另一个方法访问此方法变量。

通常我会像这样将变量声明为 class 字段 private var pitch 但似乎你不能用方法 var 来做到这一点。

有人知道我如何从其他方法访问变量或变量的值吗?

这是创建 pitch 并分配音高值的方法:

private void Myo_OrientationDataAcquired(object sender, OrientationDataEventArgs e)
        {
            const float PI = (float)System.Math.PI;

            var pitch = (int)((e.Pitch + PI) / (PI * 2.0f) * 10);

        }

然后我想要访问该值的方法如下,但是当我尝试引用 pitch 它时 doesn't exist in the current context:

private void Pose_Triggered(object sender, PoseEventArgs e)
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {

                poseStatusTbx.Text = "{0} arm Myo holding pose {1}" + e.Myo.Arm + e.Myo.Pose;
                //error trying to reference pitch here.
                pitch = pitchDefault;


            }));    
        }

总之,必须要用字段(或者属性),不能用var:

private int pitch = 0;

var 仅表示 "let the compiler decide what the type should be" - 它本身不是 "variant" 或类型。

由于您要投射到 int,只需添加一个私有 int 字段:

private int pitch;

private void Myo_OrientationDataAcquired(object sender, OrientationDataEventArgs e)
{
    const float PI = (float)System.Math.PI;

    pitch = (int)((e.Pitch + PI) / (PI * 2.0f) * 10);

}

private void Pose_Triggered(object sender, PoseEventArgs e)
{
    App.Current.Dispatcher.Invoke((Action)(() =>
    {
        poseStatusTbx.Text = "{0} arm Myo holding pose {1}" + e.Myo.Arm + e.Myo.Pose;
        //error trying to reference pitch here.
        pitch = pitchDefault;
    }));    
}

var 不是类型,它是一个关键字,这意味着将从语句的右侧部分推断出变量的类型

在你的情况下 pitch 将是 Int32 类型

要解决您的问题,请在 Myo_OrientationDataAcquired

之外的 class 中定义一个私有变量
int pitch;
private void Myo_OrientationDataAcquired(object sender, OrientationDataEventArgs e)
    {
        float PI = (float)System.Math.PI;

        pitch = (int)((e.Pitch + PI) / (PI * 2.0f) * 10);

    }