我在Xamarin.Forms中有一个IService
,看起来像这样:
namespace MyProject.Main
{
public delegate void XChanged();
public delegate void YChanged();
public delegate void ZChanged();
public interface IOrientationSensor
{
double X { get; set; }
double Y { get; set; }
double Z { get; set; }
event XChanged OnXChanged;
event YChanged OnYChanged;
event ZChanged OnZChanged;
void Start();
void Stop();
}
}
我首先尝试将我的委托放到接口中-但是Visual Studio抱怨它-所以我读到它们可以放到命名空间中。
现在在我的Service
iOS实施中,我可以触发OnChangedX
:
[assembly: Dependency(typeof(OrientationSensor)) ]
namespace MyProject.iOS
{
public class OrientationSensor : IOrientationSensor
{
CMMotionManager motionManager = new CMMotionManager();
NSOperationQueue queue = new NSOperationQueue();
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public event XChanged OnXChanged;
public event YChanged OnYChanged;
public event ZChanged OnZChanged;
public void Start()
{
motionManager.StartDeviceMotionUpdates(queue, DataUpdated);
}
public void Stop()
{
motionManager.StopDeviceMotionUpdates();
}
void DataUpdated(CMDeviceMotion data, NSError error)
{
if (data == null)
return;
// OnChangedX() works
// OnChangedY() crashes
// OnChangedZ() crashes
}
}
}
Y和Z崩溃,并显示以下消息:
对象引用未设置为对象的实例
...发射X时有效。
有人可以帮忙解释一下为什么我似乎仅限于仅使用1个代表吗?
答案 0 :(得分:0)
我刚刚意识到我已经为OnXChanged
分配了事件处理程序,但没有为OnYChanged
和OnZChanged
分配事件处理程序。分配事件处理程序显然可以提供事件值:
public static void UseSensors()
{
var orientationSensor = DependencyService.Get<IOrientationSensor>();
orientationSensor.OnXChanged += () =>
{
};
/* did not realize these where needed for OnChangedY and OnChangedZ to stop being null
orientationSensor.OnYChanged += () =>
{
};
orientationSensor.OnZChanged += () =>
{
};
*/
orientationSensor.Start();
}