public Control? Build(object? param) { if (param != null && param is ViewModelBase) { var viewModelType = param.GetType(); if (_viewModelViewMappings.TryGetValue(viewModelType, outvar viewType)) { return (Control)Activator.CreateInstance(viewType)!; // 这里使用了反射 } returnnew TextBlock { Text = "Not Found: " + viewModelType.FullName }; } returnnull; }
修改后使用工厂方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public Control? Build(object? param) { if (param != null && param is ViewModelBase) { var viewModelType = param.GetType(); if (_viewModelViewMappings.TryGetValue(viewModelType, outvar viewFactory)) { return viewFactory(); // 使用了工厂方法 } returnnew TextBlock { Text = "Not Found: " + viewModelType.FullName }; } returnnull; }
这样就可以消除反射了
问题2: 关闭特定库的剪裁
发布时我注意到很多这样的剪裁警告
1 2 3 4 5
2>Assembly 'Serilog' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries 2>Assembly 'ReactiveUI' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries 2>Assembly 'SukiUI' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries 2>Assembly 'Avalonia.Controls.DataGrid' produced trim warnings. For more information see https://aka.ms/dotnet-illink/libraries 2>Assembly 'Avalonia.Controls.DataGrid' produced AOT analysis warnings.
其中<TextBlock Text="{Binding Name}"/>和Text="{Binding Id}"/>产生了报错AVLN2000 Unable to resolve property or method of name 'Id' on type 'XamlX.TypeSystem.XamlPseudoType'.,查看类型ExploreViewModel,定义大概如下
1 2 3 4 5 6 7 8 9
publicclassExploreViewModel : ViewModelBase { public A[] B { get; set; } = new A[] { ... }; }