确定一个setter内来电者 - 或者设置属性,悄无声息 [英] Determining the caller inside a setter -- or setting properties, silently

查看:112
本文介绍了确定一个setter内来电者 - 或者设置属性,悄无声息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,当一个属性的变化,有没有什么办法来确定改变的鼻祖?换句话说,在下面的视图模型,我就喜欢的PropertyChanged事件的发件人的说法是那个叫为prop1 二传手实际的对象:

Given a standard view model implementation, when a property changes, is there any way to determine the originator of the change? In other words, in the following view model, I would like the "sender" argument of the "PropertyChanged" event to be the actual object that called the Prop1 setter:

public class ViewModel : INotifyPropertyChanged
{
    public double Prop1
    {
        get { return _prop1; }
        set
        {
            if (_prop1 == value)
                return;
            _prop1 = value;

            // here, can I determine the sender?
            RaisePropertyChanged(propertyName: "Prop1", sender: this);
        }
    }
    private double _prop1;

    // TODO implement INotifyPropertyChanged
}



另外,是它可以适用 CallerMemberNameAttribute 来属性setter?

Alternatively, is it possible to apply CallerMemberNameAttribute to a property setter?

推荐答案

如果我正确地理解,你问的是二传的调用者。这意味着,在调用堆栈获得的二传手本身(这也太方法)之前,前面的方法调用。

If I understood correctly, you're asking about the caller of the setter. That means, the previous method call in the call stack before getting to the setter itself (which is a method too).

使用 StackTrace.GetFrames 此方法。例如(从 http://www.csharp-examples.net/reflection-callstack/ 拍摄):

Use StackTrace.GetFrames method for this. For example (taken from http://www.csharp-examples.net/reflection-callstack/):

using System.Diagnostics;

[STAThread]
public static void Main()
{
  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
}

输出:

Main
nExecuteAssembly
ExecuteAssembly
RunUsersAssembly
ThreadStart_Context
Run
ThreadStart

基本上,你问什么会是 stackFrames [1 ] .GetMethod()。名称

Basically, what you're asking for would be stackFrames[1].GetMethod().Name.

这篇关于确定一个setter内来电者 - 或者设置属性,悄无声息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆