2013-05-10 69 views
0

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

例如:

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

为什么你不能将它们作为参数发送? – PoweredByOrange 2013-05-10 16:11:05

+0

'someVar'和'anotherVar'是否允许有相同的基类? – 2013-05-10 16:15:53

+0

@ programmer93,因为在一个用于大量项目的程序集中,我无法重建所有这些程序。 – NioZero 2013-05-10 16:56:07

回答

2

您可以使用与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 
    { 
    } 
} 
+0

是的,“using”的全部要点是确定性地调用清理代码,其中可以包括重置上下文。请注意,虽然这也许你应该使用一个堆栈,而不是一个变量。 – 2013-05-10 16:29:52

+0

@Ben:恩......实质上我正在使用一个堆栈。每个上下文都堆叠在另一个上面,并保存对上一个上下文的引用。第一个上下文有对'null'的引用。将它看作一个“链接堆栈”,其中构造函数像“Push”一样工作,而“Dispose”则像“Pop”一样工作。 – 2013-05-10 16:33:34

+0

啊,我错过了你实现了你自己的单链表。是的,就像一个堆栈会照顾嵌套。 – 2013-05-10 16:35:18

0

创建您可以从Someclass.OtherFunction内访问变量公共的getter(),并设置取决于什么功能所做的调用,这样你就可以识别呼叫者的变量值。

相关问题