确定 setter 中的调用者 - 或设置属性,静默 [英] Determining the caller inside a setter -- or setting properties, silently
问题描述
给定一个标准的视图模型实现,当一个属性发生变化时,有没有办法确定变化的发起者?换句话说,在下面的视图模型中,我希望PropertyChanged"事件的sender"参数是调用 Prop1
setter 的实际对象:
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
应用于属性设置器?
Alternatively, is it possible to apply CallerMemberNameAttribute
to a property setter?
推荐答案
如果我理解正确,您是在询问 setter 的调用者.这意味着,在到达 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().Name
.
这篇关于确定 setter 中的调用者 - 或设置属性,静默的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!