我正在尝试访问存储在方法变量var pitch
中的值,但我不确定如何从其他方法访问此方法变量。
通常我会将变量声明为类似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;
}));
}
答案 0 :(得分:3)
简而言之,您必须使用字段(或属性),而不能使用var
:
private int pitch = 0;
答案 1 :(得分:1)
var
只是意味着"让编译器决定类型应该是什么" - 它不是"变种"或者本身就是一种类型。
由于您要投放到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;
}));
}
答案 2 :(得分:1)
var不是一个类型,它是一个关键字,意味着变量的类型将来自语句的右边部分
在您的情况下,音高将是Int32类型
解决您的问题,在Myo_OrientationDataAcquired之外的类中定义一个私有变量
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);
}