是否有可能从另一个函数中检测到使用的变量并访问该变量?

本文关键字:变量 访问 有可能 另一个 函数 检测 是否 | 更新日期: 2023-09-27 18:12:57

我有一个函数调用另一个函数。我想知道,在第二个函数中,我是否可以检测到它是否从using作用域中的第一个函数调用。如果我能检测到它,我就想访问using作用域中的变量。我不能通过参数发送变量。

例如:

// Normal call to OtherFunction
void function1()
{
    SomeClass.OtherFunction();
}

// Calling using someVar
void function2()
{
    using(var someVar = new someVar())
    {
        SomeClass.OtherFunction();
    }
}
// Calling using other variable, in this case, similar behaviour to function1()
void function3()
{
    using(var anotherVar = new anotherVar())
    {
        SomeClass.OtherFunction();
    }
}
class SomeClass
{
    static void OtherFunction()
    {
         // how to know if i am being called inside a using(someVar)
         // and access local variables from someVar
    }
}

是否有可能从另一个函数中检测到使用的变量并访问该变量?

您可以使用与System.Transaction.TransasctionScope相同的机制。只有当所有上下文都可以有相同的基类时,这才有效。基类在构造过程中将自己注册到一个静态属性中,并随时删除自己。如果另一个Context已经激活,它将被抑制,直到最新的Context再次被处置。

using System;
namespace ContextDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DetectContext();
            using (new ContextA())
                DetectContext();
            using (new ContextB())
                DetectContext();
        }
        static void DetectContext()
        {
            Context context = Context.Current;
            if (context == null)
                Console.WriteLine("No context");
            else 
                Console.WriteLine("Context of type: " + context.GetType());
        }
    }
    public class Context: IDisposable
    {
        #region Static members
        [ThreadStatic]
        static private Context _Current;
        static public Context Current
        {
            get
            {
                return _Current;
            }
        }
        #endregion
        private readonly Context _Previous;
        public Context()
        {
            _Previous = _Current;
            _Current = this;
        }
        public void Dispose()
        {
            _Current = _Previous;
        }
    }
    public class ContextA: Context
    {
    }
    public class ContextB : Context
    {
    }
}

为您可以从Someclass.OtherFunction()中访问的变量创建公共getter,并根据执行调用的函数设置变量值,以便您可以识别调用者。