我有一个名为MyProperty
的属性。我有兴趣获取对调用属性的setter的对象的引用。例如:
MyProperty
{
set
{
if (modifer.GetType() == typeof(UIControl))
{
//some code
}
else
{
//some code
}
}
}
答案 0 :(得分:0)
除非你放松堆叠,否则我认为这是不可能的?你可以做什么,但我不推荐它。
答案 1 :(得分:0)
你可以利用反射。虽然这种做法不是我推荐的。
StackTrace stackTrace = new StackTrace();
var modifier = stackTrace.GetFrame(1).GetType();
if (modifier == typeof(UIControl))
{
//some code
}
我没有测试过,但应该是正确的。
您还可以查看CallerMemberNameAttribute,它可能与您相关。
答案 2 :(得分:0)
可以在运行时检查当前堆栈。这将使您能够检查调用方法的类:
StackTrace stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(1).GetMethod();
var callingType = callingMethod.ReflectedType
//Or possible callingMethod.DeclaringType, depending on need
但是,这种类型的代码应该设置警报。使用反射来展开堆栈是脆弱的,不直观的,并且无视separation of concerns。属性的setter是一个抽象,旨在设置除了要设置的值以外的值。
有几个更强有力的选择。其中,考虑使用仅由UIControls
调用的方法:
public void SetMyPropertyFromUiControl(MyType value)
{
this.MyProperty = value;
... other logic concerning UIControl
}
如果用于设置属性的UIControl
实例的详细信息很重要,则方法签名可能如下所示:
public void SetMyPropertyFromUiControl(MyType value, UIControl control)
{
this.MyProperty = value;
... other logic concerning UIControl that uses the control parameter
}
答案 3 :(得分:0)
实际上.NET 4.5中有一个新功能,称为“来电者信息”。
您可以获得有关此类来电者的一些信息:
public Employee([CallerMemberName]string sourceMemberName = "",
[CallerFilePath]string sourceFilePath = "",
[CallerLineNumber]int sourceLineNo = 0)
{
Debug.WriteLine("Member Name : " + sourceMemberName);
Debug.WriteLine("File Name : " + sourceFilePath);
Debug.WriteLine("Line No. : " + sourceLineNo);
}