【发布时间】:2020-03-13 10:19:00
【问题描述】:
我写了如下扩展方法:
public static void NotifyChanged<T>(this INotifyPropertyChanged inpc, ref T current, T newValue, Action<PropertyChangedEventArgs> eventRaiser, [CallerMemberName] string? name = null) where T : IEquatable<T> {
if (current.Equals(newValue)) { return; }
current = newValue;
eventRaiser(new PropertyChangedEventArgs(name));
}
可以这样使用:
public class Foo : Bar, INotifyPropertyChanged {
public event PropertyChangedEventHandler? PropertyChanged;
private string? rootExpression;
public string? RootExpression {
get => rootExpression;
set => this.NotifyChanged(ref rootExpression, value, args => PropertyChanged?.Invoke(this, args));
}
}
这节省了编写 INPC 感知属性的大部分样板文件。
但是,我现在在调用 NotifyChanged 时收到编译器警告错误:
类型“字符串?”不能在泛型类型或方法“INotifyPropertyChangedExtensions.NotifyChanged(INotifyPropertyChanged, ref T, T, Action, string?)”中用作类型参数“T”。类型参数“字符串”的可空性?与约束类型“System.IEquatable”不匹配。
AFAICT 错误是说 string? 不能转换为 IEquatable<string?>,只有 string 可以转换为 IEquatable<string>。
我该如何解决这个问题?应用一些属性?还是别的什么?
【问题讨论】:
标签: c# nullable-reference-types