如何修复Xamarin中‘DATA是类型,在此上下文无效’的错误
问题原因与修复方案
你遇到的这个错误其实是个典型的C#语法误解,咱们一步步来解决:
直接错误原因
报错 "'DATA' is a type, which is not valid in the given context" 是因为你在 File.ReadAllText(DATA) 里传入了类类型DATA,但File.ReadAllText方法需要的是字符串格式的文件路径——你把自己定义的实体类当成了文件路径参数,编译器当然会报错啦。
修复步骤
1. 替换为正确的JSON文件路径
首先你得明确你的JSON数据文件存在哪里,然后用对应的方式读取它:
情况1:JSON文件是项目嵌入式资源
如果你的JSON文件(比如叫places.json)是放在项目里作为嵌入式资源,需要这样读取:
// 先引入System.Reflection命名空间 var assembly = typeof(MapPage).GetTypeInfo().Assembly; string json; // 这里的路径格式是「命名空间.文件名」,比如你的命名空间是Orbage,文件是places.json,就是Orbage.places.json using (Stream stream = assembly.GetManifestResourceStream("Orbage.places.json")) using (StreamReader reader = new StreamReader(stream)) { json = reader.ReadToEnd(); }
情况2:JSON文件在应用本地存储文件夹
如果文件是保存在应用的私有存储目录里,用这个方式获取路径:
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "places.json"); var json = File.ReadAllText(filePath);
2. 优化代码里的其他小问题
除了这个语法错误,你的代码还有几个可以优化的地方,避免后续踩坑:
- 不要在循环里覆盖CustomPins:你现在每次循环都会把
customMap.CustomPins重新赋值为新列表,最后只会留下最后一个Pin。应该先初始化列表,再逐个添加:// 循环前先初始化 customMap.CustomPins = new List<CustomPin>(); foreach (var place in places) { // ... 创建pin的代码 ... customMap.CustomPins.Add(pin); customMap.Pins.Add(pin); } - MoveToRegion移到循环外:地图定位只需要执行一次,放在循环外面更高效。
- 解析数值时指定文化格式:
double.Parse最好加上CultureInfo.InvariantCulture,避免不同区域设置下的解析错误:Position = new Position(double.Parse(place.Lat, CultureInfo.InvariantCulture), double.Parse(place.Lng, CultureInfo.InvariantCulture))
3. (可选但推荐)遵循C#命名规范
C#里类名一般用PascalCase(首字母大写,其他单词首字母也大写),所以把DATA改成Data会更符合行业规范,代码可读性也更好。
修改后的完整代码示例
这里给出用嵌入式资源读取的完整MapPage代码:
using System.Collections.Generic; using Xamarin.Forms.Maps; using Xamarin.Forms; using System.IO; using Newtonsoft.Json; using System; using System.Reflection; using System.Globalization; namespace Orbage { class MapPage : ContentPage { public MapPage() { CustomMap customMap = new CustomMap { MapType = MapType.Street }; // 读取嵌入式JSON资源 var assembly = typeof(MapPage).GetTypeInfo().Assembly; string json; using (Stream stream = assembly.GetManifestResourceStream("Orbage.places.json")) using (StreamReader reader = new StreamReader(stream)) { json = reader.ReadToEnd(); } var places = JsonConvert.DeserializeObject<List<DATA>>(json); // 初始化CustomPins列表 customMap.CustomPins = new List<CustomPin>(); foreach (var place in places) { CustomPin pin = new CustomPin { Type = PinType.Place, Position = new Position(double.Parse(place.Lat, CultureInfo.InvariantCulture), double.Parse(place.Lng, CultureInfo.InvariantCulture)), Label = place.Label, Address = place.Address, Name = "Xamarin", Url = "http://xamarin.com/about/" }; customMap.CustomPins.Add(pin); customMap.Pins.Add(pin); } // 只执行一次地图定位 customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0))); Content = customMap; } } }
内容的提问来源于stack exchange,提问作者ItsRaptorman
相关产品推荐
相关产品推荐

