C# 是否可以从另一个函数检测using的变量并访问该变量?

C# 是否可以从另一个函数检测using的变量并访问该变量?,c#,scope,using,C#,Scope,Using,我有一个函数调用另一个函数。我想知道,在第二个函数中,我是否可以检测到它是否在使用范围内从第一个函数调用。如果我能检测到它,我想使用作用域访问该范围内的变量。我无法通过参数发送变量 例如: // Normal call to OtherFunction void function1() { SomeClass.OtherFunction(); } // Calling using someVar void function2() { using(var someVar = n

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

例如:

// 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
    }
}

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

您可以使用与
System.Transaction.TransasctionScope
相同的机制。只有当所有上下文都可以具有相同的基类时,这才有效。基类在构造期间在静态属性中注册自己,并在dispose中移除自己。如果另一个
上下文
已处于活动状态,则会一直保持该状态,直到再次释放最新的
上下文

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
    {
    }
}

为什么不能将它们作为参数发送?是否允许
someVar
anotherVar
具有相同的基类?@programmer93,因为它位于一个在许多项目中使用的程序集中,而我无法重建所有的基类是的,
使用
的整个要点是它确定地调用清理代码,这可能包括重置上下文。不过请注意,也许您应该使用堆栈,而不仅仅是单个变量。@Ben:嗯。。。本质上,我使用的是堆栈。每个上下文堆叠在另一个上下文上,并保存对前一个上下文的引用。第一个上下文引用了
null
。将其视为一个“链接堆栈”,其中构造函数的作用类似于一个
Push
,而
Dispose
的作用类似于一个
Pop
。啊,我没想到你实现了自己的单链接列表。是的,这就像堆栈一样负责嵌套。