如何修复Xamarin Forms项目中CS0618(等级2)过时警告?
修复Xamarin.Forms中CS0618过时警告的方案
你碰到的这个CS0618警告,是因为你代码里用的BindableProperty.Create<CustomWebView, string>这个泛型重载已经被Xamarin.Forms标记为过时啦。现在官方推荐用更简洁、更高效的重载方式来创建绑定属性,我给你两种修复方案:
方案一:使用非泛型的Create方法(最推荐)
把原来的泛型写法换成基于nameof运算符的重载,代码可读性更高,也完全符合最新的规范:
public class CustomWebView : WebView { public static readonly BindableProperty UriProperty = BindableProperty.Create( nameof(Uri), typeof(string), typeof(CustomWebView), default(string)); public string Uri { get => (string)GetValue(UriProperty); set => SetValue(UriProperty, value); } }
方案二:使用更新的泛型重载
如果你习惯用泛型写法,也可以用这种更简洁的泛型重载(同样不会触发过时警告):
public class CustomWebView : WebView { public static readonly BindableProperty UriProperty = BindableProperty.Create( propertyName: nameof(Uri), returnType: typeof(string), declaringType: typeof(CustomWebView), defaultValue: default(string)); public string Uri { get => (string)GetValue(UriProperty); set => SetValue(UriProperty, value); } }
为什么会触发警告?
旧的带表达式树的泛型重载BindableProperty.Create<TSource, TProperty>(Expression<Func<TSource, TProperty>>, TProperty)已经被官方弃用,一方面是因为表达式树会带来不必要的性能消耗,另一方面用nameof能更直观地关联属性名称,减少出错概率。
内容的提问来源于stack exchange,提问作者Ishara Lakshitha
相关产品推荐
相关产品推荐

