我一直在搞乱默认的接口实现。认为您必须向下转换为接口类型才能使用默认方法实现。我还发现了一堆关于另一种语法的注释,我找不到这是否已经包含在内,我确实找到了关于它的外观的“决定”,但是它不起作用。我做错了吗?还是这个新语法尚未包含在内?
有些相关但没有回答我的问题:从实现结构中调用 C# 接口默认方法而不进行装箱 https://stackoverflow.com/questions/57827493/calling-c-sharp-interface-default-method-from-implementing-struct-without-boxing
注释base<>/base()
句法:https://github.com/dotnet/csharplang/blob/master/meetings/2018/LDM-2018-11-14.md#default-interface-implementations https://github.com/dotnet/csharplang/blob/master/meetings/2018/LDM-2018-11-14.md#default-interface-implementations
微软关于该提案的页面:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
class D : IA, IB, IC
{
//Notice the use of base() right here.
void IA.M() { base(IB).M(); }
}
假设我们需要对某个对象进行 INotifyPropertyChanged。我们现在可以在接口上默认实现 SetField :
public interface INotify : INotifyPropertyChanged
{
void InvokePropertyChanged(string propertyName);
bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
INotify thing = (INotify)this;
if (propertyName == null)
{
throw new ArgumentException($"{nameof(propertyName)} is null. PropertyChangedEventHandler will not be fired correctly.");
}
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
InvokePropertyChanged(propertyName);
return true;
}
}
实现它需要沮丧(((INotify)this).SetField
), 使用base(INotify)
会优先选择这里。
public class Thing : INotify
{
public string A
{
get => _a;
//Need an explicit cast here. Can't figure out how to use base syntax.
set => ((INotify)this).SetField(ref _a, value);
}
private string _a;
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}