简体   繁体   English

在助手类中使用静态方法与非静态方法

[英]Using Static methods in the helper class vs non-static

I have a helper class that takes some object, processes it and returns back some instance of the other class or even the List of the objects. 我有一个帮助器类,它接收一些对象,对其进行处理,然后返回其他类的某些实例,甚至返回对象的列表。 What would be the best way: to make this helper method static or non-static? 最好的方法是什么:将此辅助方法设为静态还是非静态? The thing is that my app can create lots of the Car objects and I was thinking whether it could have a negative effect when each of them use the static helper? 问题是我的应用程序可以创建许多Car对象,而我在考虑当每个对象使用静态助手时是否会对它们产生负面影响?

Most helper or utility classes use static methods. 大多数帮助程序或实用程序类都使用静态方法。 You should only use non-static methods if you want to create multiple instances of your helper class, but since you just need a simple input -> function -> output, I would make the methods static. 如果要创建助手类的多个实例,则仅应使用非静态方法,但是由于只需要一个简单的input-> function-> output,因此我将这些方法设为静态。

Probably this is something that can be solved without deciding the helper object's life-cycle where you require it. 可能无需确定辅助对象的生命周期就可以解决此问题。

You should try to leverage dependency injection approach: 您应该尝试利用依赖注入方法:

public class X
{
   public X(IHelper helper)
   {
        Helper = helper;
   }

   private IHelper Helper { get; }

   public void DoStuff() 
   {
        var result = Helper.DoOtherStuff(input);
   }
}

That is, X don't know whether Helper is always the same instance or if it's a transient object. 也就是说, X不知道Helper是否始终是同一实例,或者它是否是瞬时对象。 This makes the code cleaner and more test-friendly, because you can mock the helper with a fake IHelper implementation to be sure that you're just testing X . 这样可以使代码更IHelper ,更易于测试,因为您可以使用伪造的IHelper实现模拟帮助程序,以确保您只是在测试X

Use static class with static methods, No instance, no derivation and only static methods in the class. 将静态类与静态方法一起使用,该类中没有实例,没有派生且只有静态方法。

public static class HelperClass
{
   public static void HelperMethod()
   {
       // do something
   } 
}

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

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