我正在使用“类型安全枚举模式”
public class Level
{
public static readonly Level Low = new Level(0, "Low");
public static readonly Level Medium = new Level(1, "Medium");
public static readonly Level High = new Level(2, "High");
private int _value;
private string name;
private Level(int value, string name)
{
_value=value;
_name=name;
}
}
出于测试目的,我需要创建一个无效的关卡,我用反射来做。
int id = -1;
string value = "invalid";
var constructor = typeof(Level).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(int), typeof(string)}, null);
var invalidLevel = (Level)constructor.Invoke(new object[] {id, value});
使用反射访问私有构造函数似乎....对我来说是错误的。有没有更好的方法来制作无效级别?