我在设计时收到错误消息


  必须完全分配PropertyChanged


在ctor中。如果不是ctor,则不会出现错误消息。

如何解决这个问题?

public struct LogCurve : INotifyPropertyChanged
{
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void Notify()
    {
        OnPropertyChanged(string.Empty);
    }
    public string Name { get; }
    public List<LogCurveDataPoint> LogPoints { get; }
    public int ServerCount { get; }
    public int Count { get { return LogPoints.Count; } }
    public double? MinValue
    {
        get
        {
            return LogPoints.Count == 0 ? (double?)null : LogPoints.Min(x => x.Value);
        }
    }
    public double? MaxValue
    {
        get
        {
            return LogPoints.Count == 0 ? (double?)null : LogPoints.Max(x => x.Value);
        }
    }
    public long? MinIndex
    {
        get
        {
            return LogPoints.Count == 0 ? (long?)null : LogPoints.Min(x => x.Index);
        }
    }
    public long? MaxIndex
    {
        get
        {
            return LogPoints.Count == 0 ? (long?)null : LogPoints.Max(x => x.Index);
        }
    }
    public LogCurve(string name, int serverCount)
    {
        Name = name;
        LogPoints = new List<LogCurveDataPoint>();
        ServerCount = serverCount;
    }
}

最佳答案

struct的所有字段都必须在其构造函数中分配。这也适用于事件。如果您不知道如何处理构造函数中的事件字段,只需将其设置为null即可:

public LogCurve(string name, int serverCount)
{
    Name = name;
    LogPoints = new List<LogCurveDataPoint >();
    ServerCount = serverCount;
    PropertyChanged = null;
}

关于c# - struct INotifyPropertyChanged不适用于ctor,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50049853/

10-12 14:13