【问题标题】:struct INotifyPropertyChanged will not work with ctorstruct INotifyPropertyChanged 不适用于 ctor
【发布时间】:2018-04-26 18:34:24
【问题描述】:

我在设计时收到错误消息

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

【问题讨论】:

  • 不是您问题的答案,但要小心:在值类型上实现 INotifyPropertyChanged 几乎肯定是个坏主意。值类型可能会被复制到您意想不到的地方,从而很容易订阅错误副本的更改。
  • @hvd 我想我要转课了。
  • 事实上,每当您将结构作为参数提供给方法时,它都会被复制。因此,当您更改结构属性值时,仅通知副本,而不是您的原始参考。

标签: c# .net struct


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2023-02-22
    • 2016-01-27
    • 2011-11-21
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    相关资源
    最近更新 更多