C# static class: 我应该将对象传递给构造函数吗?
C# static class: should I pass the object to the constructor?
我有一个静态的 class(称为 Utils),其中包含一些不与任何特定对象关联的实用方法。然而,这些方法中的大多数都引用了同一个对象。
public static string Method1(Context context)
{......}
public static string Method2(Context context, Etc etc)
{......}
public static string Method3(Context context)
{......}
这个(上下文)对象是在系统的主要 class 中创建的。但是这些静态方法在以后的事件中用于系统的不同部分。我应该在 Utils class 中创建一个静态构造函数并从主 class 初始化上下文对象吗?还是我应该让调用这些静态方法的每个 class 都传递上下文对象,因为它们已经引用了上下文对象?每种方法的优缺点是什么?
编辑:顺便说一下,如果有人好奇的话,这是一个 Xamarin.Android 项目。
Most of those methods however take a reference to the same object.
这通常是一个非常强烈的迹象,表明 (1) 实用程序 class 中的方法可能不合适,或者 (2) 实用程序 class 不应该是静态的。
Should I create a static constructor in the Utils class and initialize the context object from the main class?
当在别处创建上下文时,这可能无法实现,因为您的实用程序 class 可能会在某个意外时间初始化。
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?
如果您决定这样做,将方法移动到 Context
中或许是个好主意,或者如果不可能,将您的实用程序方法移动到扩展方法中:
public static string Method1(this Context context) {
...
}
这可以让您节省打字时间,因为您不必拼出实用程序的名称 class。
我有一个静态的 class(称为 Utils),其中包含一些不与任何特定对象关联的实用方法。然而,这些方法中的大多数都引用了同一个对象。
public static string Method1(Context context)
{......}
public static string Method2(Context context, Etc etc)
{......}
public static string Method3(Context context)
{......}
这个(上下文)对象是在系统的主要 class 中创建的。但是这些静态方法在以后的事件中用于系统的不同部分。我应该在 Utils class 中创建一个静态构造函数并从主 class 初始化上下文对象吗?还是我应该让调用这些静态方法的每个 class 都传递上下文对象,因为它们已经引用了上下文对象?每种方法的优缺点是什么?
编辑:顺便说一下,如果有人好奇的话,这是一个 Xamarin.Android 项目。
Most of those methods however take a reference to the same object.
这通常是一个非常强烈的迹象,表明 (1) 实用程序 class 中的方法可能不合适,或者 (2) 实用程序 class 不应该是静态的。
Should I create a static constructor in the Utils class and initialize the context object from the main class?
当在别处创建上下文时,这可能无法实现,因为您的实用程序 class 可能会在某个意外时间初始化。
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?
如果您决定这样做,将方法移动到 Context
中或许是个好主意,或者如果不可能,将您的实用程序方法移动到扩展方法中:
public static string Method1(this Context context) {
...
}
这可以让您节省打字时间,因为您不必拼出实用程序的名称 class。