无法从部分 class 调用事件

Invoking an event from partial class is not possible

我有以下 class 结构:

    public abstract class Base : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    }
    
    internal partial class ImplBase : Base {
    }
    
    internal partial class ImplBase {
        void someFunc(){
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("propName"));
        }
    }

为什么语言不允许从部分 class 引发事件?

在此处查看代码段:https://dotnetfiddle.net/k8catR

这与它是部分内容没有任何关系class。这与您尝试从未定义的 class 中提高偶数有关。下面不会引发任何错误。

public partial class Base : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


}

public partial class Base
{
    protected void RaiseEvent(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("propertyName"));
    }
}

internal partial class ImplBase : Base
{
}

internal partial class ImplBase
{
    void someFunc()
    {
        RaiseEvent("propName");
    }
}

可以重现没有部分编译的错误 class :

public abstract class Base : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
}

internal class ImplBase : Base
{
    void someFunc()
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("propName"));
    }
}

此代码具有相同的错误消息,它不是部分 class 限制。这是一个传统限制:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-raise-base-class-events-in-derived-classes

When you create a class that can be used as a base class for other classes, you should consider the fact that events are a special type of delegate that can only be invoked from within the class that declared them. Derived classes cannot directly invoke events that are declared within the base class. Although sometimes you may want an event that can only be raised by the base class, most of the time, you should enable the derived class to invoke base class events. To do this, you can create a protected invoking method in the base class that wraps the event. By calling or overriding this invoking method, derived classes can invoke the event indirectly.

您需要在声明事件的 class 中引发事件。您可以在方法中执行此操作并在 sub-classes 中重复使用该方法:

public abstract class Base : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

internal partial class ImplBase : Base
{ }

internal partial class ImplBase
{
    void someFunc()
    {
        RaisePropertyChanged("propName");
    }
}