简体   繁体   English

C#如何实现“单一”方法

[英]C# how to implement “singleton” method

We all know about the singleton pattern. 我们都知道单例模式。

How do you implement a singleton "method"? 您如何实现单例“方法”? - a method that is called only once and any other call will do nothing. -仅被调用一次的方法,任何其他调用都将无效。

I can think a few ways (including Lazy - if (!.IsValueCreated) {... value.method();}) but how would you implement it? 我可以考虑几种方法(包括惰性-if(!.IsValueCreated){... value.method();}),但是您将如何实现呢?

I don't think so there is something like a singleton method. 我不认为有类似单例方法的事情。

If you want your method to do execute the block of code only once then you can do that. 如果您希望您的方法只执行一次代码块,则可以这样做。 This can be done in several ways, one of them could be as follows- 这可以通过多种方式完成,其中一种可能是:

   public class Foo
    {
      private static bool _isInitialied;


      public void Initialize()
      {
        if(_isInitialied) 
            return;
        //TODO: Initialization stups.
        _isInitialied = true;
      }
    }

You could achieve this using actions: 您可以使用以下操作来实现此目的:

public class Test
{
    private Action _action;

    private void DoSomething()
    { 
        // Do something interesting
        _action = DoNothing;
    }

    private void DoNothing()
    {
    }

    public Test()
    {
        _action = DoSomething;
    }

    public void Call()
    {
        _action();
    }
} // eo class Test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM