你可以做这样的事情,但是会很乏味。
这个想法是在您将枚举导入新项目时使用您的项目设置来允许更改。
首先,您需要 2 个属性:
// This one is to indicate the format of the keys in your settings
public class EnumAttribute : Attribute
{
public EnumAttribute(string key)
{
Key = key;
}
public string Key { get; }
}
// This one is to give an id to your enum field
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueAttribute : Attribute
{
public EnumValueAttribute(int id)
{
Id = id;
}
public int Id { get; }
}
那么,这个方法:
// This method will get your attribute value from your enum value
public object GetEnumAttributeValue<TEnum>(TEnum value)
{
var enumAttribute = (EnumAttribute)typeof(TEnum)
.GetCustomAttributes(typeof(EnumAttribute), false)
.First();
var valueAttribute = (EnumValueAttribute)typeof(TEnum).GetMember(value.ToString())
.First()
.GetCustomAttributes(typeof(EnumValueAttribute), false)
.First();
return Settings.Default[String.Format(enumAttribute.Key, valueAttribute.Id)];
}
我没有检查类型是否正确,即使它找到任何属性也没有。你必须这样做,否则如果你没有提供正确的类型,你会得到一个异常。
现在,您的枚举将如下所示:
[Enum("Key{0}")]
public enum MyEnum
{
[EnumValue(0)] First,
[EnumValue(1)] Second
}
最后,在您的项目设置中,您必须添加与枚举中的成员数量一样多的行。
您必须使用与 EnumAttribute 的参数相同的模式来命名每一行。这里是“Key{0}”,所以:
- Key0:您的第一个值
- Key1:你的第二个值
- 等等……
像这样,您只需更改设置值(NOT THE KEY)即可导入您的枚举并将您的属性更改为另一个项目。
用法:
/*Wherever you put your method*/.GetEnumAttributeValue(MyEnum.First);
它将返回“您的第一个值”。