B. *_*non 0 c# geolocation coordinates nullreferenceexception windows-phone-8
在此事件处理程序中:
public static void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
DateTimeOffset timeStampUTC = args.Position.Coordinate.Timestamp.ToUniversalTime();
DateTimeOffset timeStampLocal = timeStampUTC.LocalDateTime;
DateTimeOffset dateTimeStampUTC = timeStampUTC.DateTime;
RecordLocation(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude,
args.Position.CivicAddress.City, args.Position.CivicAddress.State, dateTimeStampUTC, timeStampLocal);
}
Run Code Online (Sandbox Code Playgroud)
...我得到了一个Null Reference Exception因为args.Position.CivicAddress是null(其余的args传递给RecordLocation()有效).我估计有时会有位置null,有时它不会.如果没有城市或国家被发现的时间,我能做些什么呢?我试图使这些字符串RecordLocation()的定义可以为空,但这不会编译.
我是否需要检查CivicAddress是否为null并创建我的RecordLocation()方法的重载版本,还是有另一种方法来处理它?
如果没有城市或国家被发现的时间,我能做些什么呢?
你只需要检查一下.例如:
if (args.Position != null && args.Position.CivicAddress != null)
{
// Now you can use args.Position.CivicAddress.State safely
}
Run Code Online (Sandbox Code Playgroud)
如果你想做很多事情args.Position,你很可能想要一个"外部"if语句 - 很可能用一个局部变量来简化事情:
var position = args.Position;
if (position != null)
{
if (position.CivicAddress != null)
{
// Use properties of position.CivicAddress
}
// Assuming Coordinate is nullable to start with, of course...
if (position.Coordinate != null)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)