在 C# 中调用任何静态方法之前初始化静态字段
Init static field befor calling any static method in C#
在我的 class 中有几个具有以下签名的方法:
public static void SomeMethod()
{
...
}
这些方法中的大多数都依赖于私有静态字段的值。
在调用任何这些静态方法之前,调用者必须有任何方法为此字段赋值。
我想要一个 Random 对象供应用程序中的所有 classes 使用。如何传递对此对象的引用以在另一个 class 的静态方法中使用它?
我在 class 中有一个带有静态方法和静态初始值设定项的私有静态字段:
public static void Init(Random random)
{
_random = random;
}
但是如何确保调用了初始化程序?在每个方法中进行检查并抛出异常,在我看来是多余的。可能还有其他选择。
终于找到了适合我的解决方案:
在包含应用程序入口点的class中定义public静态属性:public static Random Rnd { get; } = new Random();
在其他classes中定义private static Random _random
;
为包含此代码的其他 classes 实现静态构造函数:
Type type = Assembly.GetExecutingAssembly().EntryPoint.DeclaringType;
var randomTypeProperties =
type.GetProperties().Where(p => p.PropertyType == typeof(Random));
foreach (var propertyInfo in randomTypeProperties)
{
_random = (Random)propertyInfo.GetValue(null);
}
我可以将来自@Andy 的消息标记为答案,因为它毕竟是一个静态构造函数。
感谢所有参与讨论的人。
学习永远不晚。昨天,当我阅读设计模式时,我意识到 Singlton 正是我所需要的:
public sealed class RandomAsSingleton : Random
{
private static volatile RandomAsSingleton _instance;
private static readonly object _syncRoot = new object();
private RandomAsSingleton() { }
public static RandomAsSingleton Instance
{
get
{
lock (_syncRoot)
{
if (ReferenceEquals(_instance, null)) { _instance = new RandomAsSingleton(); }
return _instance;
}
}
}
}
我以前的解决方案现在看来有点难看。
您可能想要使用静态构造函数
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
// set your private static field
}
在我的 class 中有几个具有以下签名的方法:
public static void SomeMethod()
{
...
}
这些方法中的大多数都依赖于私有静态字段的值。 在调用任何这些静态方法之前,调用者必须有任何方法为此字段赋值。
我想要一个 Random 对象供应用程序中的所有 classes 使用。如何传递对此对象的引用以在另一个 class 的静态方法中使用它? 我在 class 中有一个带有静态方法和静态初始值设定项的私有静态字段:
public static void Init(Random random)
{
_random = random;
}
但是如何确保调用了初始化程序?在每个方法中进行检查并抛出异常,在我看来是多余的。可能还有其他选择。
终于找到了适合我的解决方案:
在包含应用程序入口点的class中定义public静态属性:
public static Random Rnd { get; } = new Random();
在其他classes中定义
private static Random _random
;为包含此代码的其他 classes 实现静态构造函数:
Type type = Assembly.GetExecutingAssembly().EntryPoint.DeclaringType; var randomTypeProperties = type.GetProperties().Where(p => p.PropertyType == typeof(Random)); foreach (var propertyInfo in randomTypeProperties) { _random = (Random)propertyInfo.GetValue(null); }
我可以将来自@Andy 的消息标记为答案,因为它毕竟是一个静态构造函数。
感谢所有参与讨论的人。
学习永远不晚。昨天,当我阅读设计模式时,我意识到 Singlton 正是我所需要的:
public sealed class RandomAsSingleton : Random
{
private static volatile RandomAsSingleton _instance;
private static readonly object _syncRoot = new object();
private RandomAsSingleton() { }
public static RandomAsSingleton Instance
{
get
{
lock (_syncRoot)
{
if (ReferenceEquals(_instance, null)) { _instance = new RandomAsSingleton(); }
return _instance;
}
}
}
}
我以前的解决方案现在看来有点难看。
您可能想要使用静态构造函数
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
// set your private static field
}