パラメータとしてのアクションを使用してメソッドをオーバーライドします

StackOverflow https://stackoverflow.com/questions/9504584

  •  14-11-2019
  •  | 
  •  

質問

私は、ユーザーが適切な変更されたイベントを簡単にユーザーにユーザーをユーザーにユーザーにユーザーをユーザーに許可させることを可能にする一連の方法を持っています。これが方法です:

public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }
.

私は時々外来行為の古い価値が必要なことが私には明らかになりました。これは私がそれをすることを意図した方法です:

public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T, T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            var oldVal = currentValue;

            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(oldVal, newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }
.

気付くように、外部機能アクションは2つのパラメータを取ります。VSは、メソッドを作成すること(赤いQWiggliesなし)を作成しましたが、最初のメソッドと2番目のメソッドの間の使用量があいまいであると言う多くのエラーをスローします。そうであれば、私が探しているものをどのように達成することができますか?

編集

これは通常の方法の通常の使用法です。

SetPropertyValue(ref _streetAddress1, value, null, () => SalesData.StreetAddress1 = value);
.

役に立ちましたか?

解決

Firstly, this is not overriding - this is overloading.

It's fine from the point of view of the method declarations - I suspect it's the call sites which are ambiguous. Unfortunately you haven't shown us any of those.

Personally I would use two different names here to keep things simpler. Overloading can be a complex business, and by the time you've got delegates involved (with anonymous functions, method group conversions etc) it's even worse than normal - and optional parameters add to the complexity too! Having methods with different names keeps things much clearer.

Alternatively, do you need to overload it at all? Can't you just have the version with the Action<T, T> and just ignore the "old" value within the callback when you don't care about it? That would simplify things.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top