【问题标题】:Property setter not accessed when the property changed by external class外部类更改属性时未访问属性设置器
【发布时间】:2014-04-15 22:37:55
【问题描述】:

我有一个用于创建 dll 的公共类。它有一个变量和一个属性。让我们假设它看起来像这样:

public class Main
{
    private int _someInt = 0;
    public int SomeInt
    {
        get { return this._someInt; }
        set
        {
            this._someInt = value;
            if (this._someInt == 1)
            {
                _someInt = 0;
            }
        }
    }
    public int ExecuteMain()
    {
        OtherClass.DoSomething(this.SomeInt);
    }
}

我还有另一个类,在 OtherClass 类的一个单独项目中,它具有静态 DoSomething 方法:

public static void DoSomething(int someInt)
{
    someInt = 1;
}

我的问题是Main 类中的SomeInt 属性被OtherClassDoSomething 方法设置为1,但这不会触发Main 类属性中的设置器。我做错了吗?

【问题讨论】:

  • 你只是在设置一个参数的值,它与你传入的值除了它的值之外没有任何关联,你可以通过ref或者找到访问变量的方法
  • 我尝试使用“out”关键字,但在这种情况下我不能使用属性。我需要在 SomeInt 更改为 1 时捕获事件。还有其他方法可以做到吗?
  • 考虑过...我将 int 包装在一个对象中。如果我没记错的话,对象是通过引用传递的,所以我应该改变值。值确实发生了变化,但我仍然无法触发 setter。

标签: c# properties


【解决方案1】:

您正在做的是将 SomeInt 按值 传递给 DoSomething 方法,该方法获取 int 的 副本 并仅更改其本地值。

你可以:

  1. 通过 ref:public static void DoSomething(ref int someInt)

  2. 传递 Main 类并更改 DoSomething 内部的值:

    public static void DoSomething(Mainclass main) {main.SomeInt = 1}

【讨论】:

  • 1.不,我可以t. I cant 传递带有 ref 或 out 的属性。 2.这就是事情,我不使用t want to create an instance of the Main class in the OtherClass, because the Main class already references the OtherClass and uses its 方法。我不想以某种循环引用结束,当代码增长时可能会出现问题。
【解决方案2】:

没有办法做到这一点,即使你通过 reference 使用 ref 关键字传递字段也不会起作用,因为你的属性有一个 setter 方法不是您的字段。您应该更改属性的值,以便执行 setter 方法并执行验证。

你可以这样做,传递你的类的当前实例而不是字段,例如:

public int ExecuteMain()
{
    OtherClass.DoSomething(this); // just pass current instance using 'this'
}

public static void DoSomething(Main obj)
{
    obj.SomeInt = 1;
}

【讨论】:

    【解决方案3】:

    如果您想让它调用设置器逻辑,一种选择是执行以下操作:

    public static void DoSomething(Action<int> setSomeInt)
    {
        setSomeInt(1);
    }
    

    然后这样称呼它:

    public int ExecuteMain()
    {
        OtherClass.DoSomething(x => this.SomeInt = x);
    }
    

    这里的概念是,您真正赋予方法的不是可以设置的变量,而是可以执行的操作。这是一个重要的区别,因为设置属性实际上是一种操作,可以有任意复杂的实现。不过,这种方法在实践中有点尴尬,因此您需要仔细考虑一下您在这里真正想要做什么,以及是否有更好的方法来表达所需的依赖关系。

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2014-09-10
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多