开发中,我们经常会设置固定的字符串用于事件系统和调用。
public staic class Const
{
public static readonly string playGame = "playGame";
public static readonly string pauseGame = "pauseGame";
}
如上面的代码,字符串的内容本身和字符串的命名一样,但却需要重复写一遍。
通过在构造函数中使用Field.SetValue,可以实现自动赋值。
static Const()
{
//获取Const类中,静态&&公有&&仅在本类中声明的变量
foreach(int filed out typeof(Const).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclareOnly).Where(o => !o.IsLiteral))
{
field.SetValue(typeof(Const), field.Name);
}
}