struct INotifyPropertyChanged不适用于ctor

时间:2018-04-26 18:34:24

标签: c# .net struct

我在设计时收到错误信息

  

必须完全分配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;
    }
}

1 个答案:

答案 0 :(得分:3)

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

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