源代码在C#中,并且有很多遗留代码。我使用带有GUI的Winforms。
我使用源代码构建程序集,但此程序集包含在两个不同的程序包中。一个包是每个人都可以下载的免费演示应用程序(FApp),第二个包是非免费且更专业的应用程序(ProApp)。因此,您了解2个软件包不具备相同的功能。
一个在ProApp中定义了一个枚举类型。我已经和FApp一起发帖了,因为并非enum中的所有值都是相关的,它们不能以GUI的形式出现。这就是我为条件编译而努力的原因。但它会导致使用枚举的方法中的编译错误。枚举用于许多代码行。现在我不确定这是个好主意。
原始代码:
public enum eCars {Toyota, Honda, Hyundai, BMW, Acura};
我不太好的解决方案: #if FApp public enum eCars {Toyota,Honda,Hyundai}; #其他 public enum eCars {Toyota,Honda,Hyundai,BMW,Acura}; #ENDIF
就像我说的那样,使用enum eCars的方法中有很多编译错误。
public static bool IsItHyundai(eCars car)
{
if (car == eCars.Hyundai)
return true;
return false;
}
你能否提出另一种解决方案。
答案 0 :(得分:1)
我的建议是在FApp中定义Enum,并让ProApp使用SAME Enum作为FApp。然后,您可以在管理使用和行为的枚举上使用属性。读取装饰每个ENUM值的属性的扩展方法可以用于指示行为。
以下是一些实施示例代码:
public class eCarsUsageAttribute : Attribute
{
public eCarsUsageAttribute() { }
public eCarsUsageAttribute(bool allowInFApp = true)
{
AllowInFApp = allowInFApp;
}
public bool AllowInFApp { get; set; }
}
public enum eCars
{
[eCarsUsageAttribute]
Toyota,
[eCarsUsageAttribute]
Honda,
[eCarsUsageAttribute(false)]
Hyundai,
[eCarsUsageAttribute]
BMW,
[eCarsUsageAttribute]
Acura
};
public static class EnumExtensions
{
public static bool AllowInFreeApp(this eCars value)
{
lock (_usageValues)
{
//reflection is somewhat expensive so I'd recommend using a local store to keep the attributes that you have already looked up
if (!_usageValues.ContainsKey(value))
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
eCarsUsageAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(eCarsUsageAttribute), false) as eCarsUsageAttribute[];
var attr = attribs.FirstOrDefault();
if (attr != null)
_usageValues[value] = attr.AllowInFApp;
else
_usageValues[value] = false;//Depends on what you want the default behavior to be
}
return _usageValues[value];
}
}
private static Dictionary<eCars, bool> _usageValues = new Dictionary<eCars, bool>();
}