我有很多常量需要在我的一个类中移动但我不允许使用成员变量。有哪些选择?
这是我最初的尝试:
private void MyConstants(out int textSize, out int paddingValue, out int borderType, ...)
{
//Set them here
}
private Method1()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
private Method2()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
//Many more methods...Just seems to repetitive.
答案 0 :(得分:1)
使用私人类或结构。
private class Variables {
public int textSize;
public int paddingValue;
public int borderValue;
}
private Variables MyConstants{
get{ return new Variables(){textSize=1, paddingValue=2, borderValue=3};}
}
答案 1 :(得分:0)
如果您需要在构造函数中初始化,请尝试使用 readonly 而不是 const 。 编辑1: 您可以创建一个包含私有词典的类:如键和值。 在其中放置一个“对象LoadConstant(string)”方法,它将撤回数据。
public static class ConstantManager {
private static Hashtable _consts = new Hashtable();
private static const keyName = "Name 1";
public static void ConstantManager()
{
_consts[keyName] = ...;
}
public static Hashtable GetConstants()
{
var _copy = new Hashtable(_consts);
return _copy;
}
}
public OtherClass{
public void Method()
{
var consts = ConstantManager.GetConstants();
var a = consts[ConstantManager.keyName];
}
}