简体   繁体   English

C# 静态类:我应该将对象传递给构造函数吗?

[英]C# static class: should I pass the object to the constructor?

I have a static class (called Utils) with a few utility methods not associated with any particular object.我有一个静态类(称为 Utils),其中包含一些与任何特定对象无关的实用程序方法。 Most of those methods however take a reference to the same object.然而,这些方法中的大多数都引用了同一个对象。

public static string Method1(Context context)
{......}

public static string Method2(Context context, Etc etc)
{......}

public static string Method3(Context context)
{......}

This (context) object is created in the main class of the system.这个(上下文)对象是在系统的主类中创建的。 But these static methods are used in different parts of the system at later events.但是这些静态方法在以后的事件中用于系统的不同部分。 Should I create a static constructor in the Utils class and initialize the context object from the main class?我应该在 Utils 类中创建一个静态构造函数并从主类初始化上下文对象吗? Or should I let each of the class that calls these static methods pass the context object since they already have a reference to it?或者我应该让调用这些静态方法的每个类都传递上下文对象,因为它们已经有了对它的引用? What are the pros and cons of each approach?每种方法的优缺点是什么?

Edit: By the way, if anyone is curious, this is a Xamarin.Android project.编辑:顺便说一下,如果有人好奇,这是一个 Xamarin.Android 项目。

Most of those methods however take a reference to the same object.然而,这些方法中的大多数都引用了同一个对象。

This is usually a very strong indication that either (1) the methods may be out of place in the utility class, or (2) the utility class should not be static.这通常是一个非常强烈的迹象,表明 (1) 方法可能在实用程序类中不合适,或者 (2) 实用程序类不应该是静态的。

Should I create a static constructor in the Utils class and initialize the context object from the main class?我应该在 Utils 类中创建一个静态构造函数并从主类初始化上下文对象吗?

This may not be possible when the context is created elsewhere, because your utility class might get initialized at some unexpected time.当上下文在别处创建时,这可能是不可能的,因为您的实用程序类可能会在某个意外的时间初始化。

Or should I let each of the class that calls these static methods pass the context object since they already have a reference to it?或者我应该让调用这些静态方法的每个类都传递上下文对象,因为它们已经有了对它的引用?

If you decide to do so, perhaps it's a good idea to move the method into Context , or if it is not possible, make your utility methods into extension methods:如果您决定这样做,也许将方法移动到Context是个好主意,或者如果不可能,则将您的实用程序方法转换为扩展方法:

public static string Method1(this Context context) {
    ...
}

This would let you save on typing, because you wouldn't have to spell out the name of your utility class.这可以让您节省打字时间,因为您不必拼出实用程序类的名称。

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

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