代码之家  ›  专栏  ›  技术社区  ›  Tornike Gomareli

在C#属性中确定setter的调用方

  •  0
  • Tornike Gomareli  · 技术社区  · 6 年前

    我正在研究一个非常传统的代码,这里耦合在上帝的层面上。所以不知怎么的,我需要得到调用属性setter的调用方的名称。

    我真的花了很多时间来寻找解决方案,我也试过堆栈帧来获得方法的名称。 From this answer

    例如

    [System.Xml.Serialization.XmlElementAttribute("orOperatorAppendixed", Form = XmlSchemaForm.Qualified)]
            public bool OrOperatorAppendixed
            {
                get { return orOperatorAppendixed; }
                set
                {
    
                    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
                    }
                    orOperatorAppendixed = value;
    
                }
            }
    

    当有人调用那个setter时,控制台消息看起来是这样的

    set_OrOperatorAppendixed
    Read52_Condition
    Read53_Alarm
    Read77_Pip
    Read152_Window
    Read152_Window
    Read159_Layout
    Read160_layout
    InvokeMethod
    UnsafeInvokeInternal
    Invoke
    InvokeReader
    Deserialize
    Deserialize
    FromXml
    layoutReceived
    processData
    dataReceived
    dataReceived
    Complete
    CompleteCallback
    RunInternal
    Run
    Run
    Complete
    ProtectedInvokeCallback
    CompletionPortCallback
    PerformIOCompletionCallback
    

    基本上,我认为这些方法名是运行时级别的方法。所以我想说的是,我希望在我的项目中得到函数的调用方名称,特别是由调用属性设置器的项目的开发人员编写的方法。

    而且,我也读过 [CallerMemberName]字符串callername=” ,但需要将CallerMemberName作为参数进行路径设置,并且我有属性,因此无法执行此操作。

    所以我希望你能理解我的核心问题是什么。也许有办法解决我的问题。

    谢谢你

    0 回复  |  直到 6 年前