【问题标题】:C# Explicit implementation of interface breaks my INotifyPropertyChanged接口的 C# 显式实现破坏了我的 INotifyPropertyChanged
【发布时间】:2013-03-10 22:23:30
【问题描述】:

这可能是一个有点愚蠢的问题,但我找不到任何解决方法或想到以下问题的任何解决方案......

  public class Example: IExample, INotifyPropertyChanged
  {
    public Example()
    {
    }

    /// Does not works properly... 
    string fooString;
    string IExample.A
    {
        get { return this.fooString; }
        set
        {
            this.fooString= value;
            onPropertyChange("A");
        }
    }

    /// Works just fine
    string fooString;
    public string A
    {
        get { return this.fooString; }
        set
        {
            this.fooString= value;
            onPropertyChange("A");
        }
    }

    PropertyChangedEventHandler propertyChangedHandler;

    private void onPropertyChange(string propertyName)
    {
        if (this.propertyChangedHandler != null)
            propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
    }

    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
    {
        add { this.propertyChangedHandler += value; }
        remove { this.propertyChangedHandler -= value; }
    }

 }

从代码中可以看出,我有一个从 INotifyPropertyChanged 实现的类 Example 和我的 IExample 接口,它有 1 个属性 A。

由于我使用的是显式接口实现,我不得不通过我的 IExample 接口

引用我的 A

这就是我的问题所在。由于 A 来自 IExamle Explicitly,当值更改时 INotifyPropertyChanged 不会被触发...

这是有道理的。

任何想法/想法如何保持显式接口实现和 INotifyPropertyChanged 并仍然完成工作?

你可能会问我为什么痴迷于显式接口实现

1) it's cool [I know horrible reason]
2) its clarity and better code readability [mostly because of this]
3) It forces you to use Interface   

顺便说一句,请随意批评 INotifyPropertyChanged 的​​实现。我觉得我可以重新实现这是一种可以处理显式继承

的方法

提前谢谢大家。

[编辑] 更改了“显式继承与显式接口实现” - 就像 Daniel 纠正了我一样,添加了隐式继承代码。显然其中一个继承应该被注释掉......

【问题讨论】:

  • 接口由类实现,而不是继承。因此它被称为显式接口实现而不是显式继承。最后,您的问题与显式接口实现无关。如果没有引发事件,那很可能是因为没有人订阅它。话虽如此,实际上并不清楚您的问题是什么。事件没有引发吗?如果是这样,你怎么知道?还是绑定控件没有更新的问题?
  • 顺便说一句:您使用显式接口实现的原因似乎很奇怪。 “1. 很酷”——你已经注意到自己不是一个理由。 “2. 它使代码更加清晰易读” - 怎么样? “3.它强迫你使用界面” - 你为什么要强迫我使用界面?在某些情况下您想这样做,但不是一般情况。
  • 是什么让你认为事件没有被触发?
  • 我看不出有多明确是“酷”,我完全不同意你的#2--MORE 代码很少有更多的“可读性”。 @DanielHilgarth 所说的一切都是正确的——与手头的实际问题无关。
  • Daniel - 当我将代码更改为隐式实现时,代码按预期工作,事件工作正常。但是一旦我将其更改为显式程序开始工作...... 1)它的个人选择 2)当我看到界面时,我立即知道对象的基础结构或至少它的一部分。我认为对象很丑,它们可能是不同事物的混合体——我更愿意看到/使用接口而不是对象。 3)背后的想法是它迫使我“编程到接口而不是实现”。

标签: c# multiple-inheritance inotifypropertychanged explicit-interface explicit-implementation


【解决方案1】:

正如我在评论中所说,您在未向我们展示的代码中一定做错了什么。这里引发了事件:

var example = new Example();
((INotifyPropertyChanged)example).PropertyChanged += OnAChanged;
((IExample)example).A = "new string";

http://ideone.com/jMpRG7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2010-10-22
    • 1970-01-01
    • 2011-02-17
    • 2020-06-14
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多