[英]Best way to structure static constant classes with common methods
我有一堆常量类,我需要它们是 static(参见下面的示例)
public class FuelTypeConstant
{
public const string Mgo = "Mgo";
public const string HeavyFuel = "HeavyFuel";
public const string Lng = "Lng";
public const string Battery = "Battery";
public const string MgoBattery = "Mgo-battery";
public const string MgoBatteryLng = "Mgo-battery-lng";
public new static Dictionary<string, string> ValuesAndDescriptions
{
get
{
return new Dictionary<string, string> {
{Mgo, "MGO"},
{HeavyFuel, "Heavy Fuel"},
{Lng, "LNG"},
{ Battery, "Battery" },
{ MgoBattery, "MGO & Battery" },
{ MgoBatteryLng, "MGO, LNG & Battery" }
};
}
}
public string GetDescription(string value)
{
return !string.IsNullOrEmpty(value) && ValuesAndDescriptions.ContainsKey(value) ? ValuesAndDescriptions[value] : null;
}
public string GetValue(string description)
{
return ValuesAndDescriptions.Where(v => v.Value == description).Select(v => v.Key).FirstOrDefault();
}
}
这些常量类中的每一个都有一个字典字段 ValuesAndDescriptions 以及两个常用方法 GetDescription 和 GetValue。
我遇到的问题是,当我将这些变量粘贴在一个公共基础 class 中时,如下所示:
public class ConstantBase
{
public static string GetDescription(string value)
{
return !string.IsNullOrEmpty(value) && ValuesAndDescriptions.ContainsKey(value) ? ValuesAndDescriptions[value] : null;
}
public static string GetValue(string description)
{
return ValuesAndDescriptions.Where(v => v.Value == description).Select(v => v.Key).FirstOrDefault();
}
public static Dictionary<string, string> ValuesAndDescriptions = new Dictionary<string, string>();
}
ValuesAndDescriptions in the base class is never populated, and I cant override it from the child class because it is a static property, and hence the methods GetValue() and GetDescription are always returning null.
我不想在每个常量 class 中复制 GetValue(0 & GetDescription(),但我不确定最佳方法。
仅供参考,常量类需要是 static 因为我需要能够像这样调用每个常量类:
FuleTypeConstant.GetValue(XXXX)
没有实际实例化任何东西。
您不需要手动填充ValuesAndDescriptions
。 您可以为此使用反射:
public static class FuelTypeConstant
{
public const string Mgo = "Mgo";
public const string HeavyFuel = "HeavyFuel";
public const string Lng = "Lng";
public const string Battery = "Battery";
public const string MgoBattery = "Mgo-battery";
public const string MgoBatteryLng = "Mgo-battery-lng";
public static readonly string Extra = "Extra"; //Won't be included during reflection
private static readonly Dictionary<string, string> ValuesAndDescriptions;
static FuelTypeConstant()
{
ValuesAndDescriptions = typeof(FuelTypeConstant)
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly)
.ToDictionary(fi => fi.Name, fi => fi.GetRawConstantValue().ToString());
}
...
}
ValuesAndDescriptions
标记为private
,因为它是一个实现细节
readonly
,因为它填充在 static 构造函数中const
字段,因此将排除其他字段(例如public static readonly string Extra = "Extra";
)ToDictionary
我将FieldInfo
对象映射到所需的格式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.