Xamarin Android发布模式下Firebase无法解析Android.Graphics.Color问题
问题:Xamarin Android发布模式下FirebaseDatabase.net无法解析Android.Graphics.Color对象
我的Xamarin Android应用中,使用FirebaseClient(FirebaseDatabase.net)时,调试模式下一切正常,但切换到发布模式重建项目后,数据类中的Android.Graphics.Color对象解析异常,其(R,G,B,A)值变为(0,0,0,0),其他属性解析正常。我已经通过将颜色保存为字符串并手动转换为Color对象解决了问题,但想了解导致这种模式差异的原因。
Firebase观察者代码
private readonly FirebaseClient firebaseClient = new FirebaseClient(...); ... firebaseClient.Child("Tables") .AsObservable<Table>() .Subscribe(d => { if (d.Object != null) { Table table = d.Object; // ... } });
Table类定义
public class Table { public int Id { get; set; } public byte SeatsNum { get; set; } public List<Guest> Guests { get; set; } [JsonConstructor] public Table(int id, byte seatsNum) { Id = id; SeatsNum = seatsNum; Guests = new List<Guest>(); } public Table(int id, byte seatsNum, List<Guest> guests) { Id = id; SeatsNum = seatsNum; Guests = guests ?? new List<Guest>(); } }
Guest类定义
public class Guest { public string Name { get; } public Color BackgroundColor { get; } public Color TextColor { get; } public List<string> Tags { get; } public int TableId { get; } public bool Checked { get; set; } public Guest(string name, int tableId) { Name = name; ColorService colorService = new ColorService(); (Color backgroundColor, Color textColor) = colorService.GetRandomColor(); BackgroundColor = backgroundColor; TextColor = textColor; Tags = new List<string>(); TableId = tableId; Checked = false; } public Guest(string name, int tableId, params string[] tags) : this(name, tableId) { Tags = tags.ToList(); } [JsonConstructor] public Guest(Color backgroundColor, bool Checked, string name, int tableId, List<string> tags, Color textColor) { Name = name; BackgroundColor = backgroundColor; TextColor = textColor; Tags = tags ?? new List<string>(); TableId = tableId; this.Checked = Checked; } }
模式差异的原因分析
- 发布模式的代码混淆与裁剪:Xamarin发布模式默认开启ProGuard/R8混淆和IL链接器裁剪。Android.Graphics.Color的内部字段或反射依赖可能被误判为无用代码而移除,导致JSON序列化器无法正确读取其RGBA值,只能生成默认的透明黑色。
- 反射行为差异:调试模式下,序列化器可以通过反射完整访问Color类的所有成员;但发布模式经过混淆后,Color类的成员名称被重命名,反射信息丢失,序列化器无法匹配到正确的属性进行解析。
- 平台类型的特殊性:Android.Graphics.Color并非普通的POCO类,包含平台相关的底层实现。发布模式的优化逻辑可能破坏了序列化器对这类平台特定类型的处理规则,而调试模式无这些限制,因此能正常解析。
内容的提问来源于stack exchange,提问作者DusanInfinity
相关产品推荐
相关产品推荐

