4

同一程序集中的两个类:Class AStatic Class B

在...的方法中ClassA,我正在调用ClassB...中的方法,但我希望仅调用一次,而不是每次调用...的方法时,ClassA我正在设置全局属性-Ran-看看该方法是否已经运行过......它工作得很好,但我觉得这不是最好的设计。我想知道是否有更好的方法可以做到这一点?

谢谢。

ClassA.MyMethod(...)
{
....
//.... 
if (ClassB.Ran != 1)
    ClassB.Foo();
....
//...
}
4

5 回答 5

9

您需要注意解释“仅一次”限制的严格程度。静态方法通常被认为是线程安全的;如果你真的想确保你的方法只运行一次,即使是在竞速线程的情况下,那么你需要使用同步机制,最简单的例子是lock

private static bool isRun = false;
private static readonly object syncLock = new object();

public void MyMethod()
{
    lock (syncLock)
    {
        if (!isRun)
        {
            Foo();            
            isRun = true;
        }
    }
}
于 2012-05-03T18:46:11.220 回答
8

我通常会这样做Lazy<T>

考虑:

public static class Test // this is your ClassB
{
    private static Lazy<string> m_Property = new Lazy<string>( ()=>
    {
        Console.WriteLine("Lazy invoked"); 
        return "hi";
    },true);
    public static string Property
    {
        get
        {
            Console.WriteLine("value request");
            return m_Property.Value;
        }
    }
}

//....consuming code, this is in your ClassA somewhere

var test1 = Test.Property; // first call, lazy is invoked
var test2 = Test.Property; // cached value is used, delgate not invoked
var test3 = Test.Property; // cached value is used, delgate not invoked
var test4 = Test.Property; // cached value is used, delgate not invoked
var test5 = Test.Property; // cached value is used, delgate not invoked

这是输出:

value request
Lazy invoked
value request
value request
value request
value request
于 2012-05-03T18:42:33.280 回答
5

您可以在类上使用私有静态字段,以便在第一次调用该方法时设置结果,防止它再次运行:

class B
{
  private static bool fooRun = false;

  public static void Foo()
  {
    if (fooRun) { return; }
    ...
    fooRun = true;
  }
}
于 2012-05-03T18:41:00.320 回答
1

只需将 bool 传递给构造函数,无论您是否希望该事物运行?就像是:

ClassA(bool runA)
{
    if (runA) 
    {
        ClassB.Foo();
    }
}
于 2012-05-03T18:38:07.450 回答
1

没有更多细节,很难说,但听起来B类中的这个方法包含某种初始化逻辑。如果是第一次引用B类时需要发生的事情,那么你可以把它放在B类的静态构造函数中。如果B类中的方法只需要在引用A类时运行,那么它可能是从 A 类的静态构造函数调用。如果在调用 A 类的某个方法之前无法调用它,并且它只能从任何地方调用一次,那么我会说你应该从内部检查 B 类中的私有静态变量该方法,如果它已经被调用,则立即返回。否则,作为最后的手段,我会说在 A 类中拥有一个私有静态变量比全局变量更可取。

In all of these cases, however, I'd say that you are creating global state, which is almost always indicative of a poor design. In my humble opinion, this kind of problem is just screaming the need for a bit of "dependency injection".

于 2012-05-03T18:55:45.030 回答