我想知道是否有办法在C#中的enum
中包含构造函数和方法。我有类似的想法:
public enum ErrorCode
{
COMMONS_DB_APP_LEVEL("Application problem: {0}", "Cause of the problem"),
COMMONS_DB_LOW_LEVEL("Low level problem: {0}", "Cause of the problem"),
COMMONS_DB_CONFIGURATION_PROBLEM("Configuration problem: {0}", "Cause of the problem");
private String message;
private String[] argumentDescriptions;
private ErrorCode(String message, String[] argumentDescriptions)
{
this.message = message;
this.argumentDescriptions = argumentDescriptions;
}
public String[] GetArgumentDescriptions()
{
return argumentDescriptions;
}
public String GetKey()
{
return argumentDescriptions();
}
public String GetMessage()
{
return message;
}
}
显然,我不能像这样写enum
。我怎么能做到这一点?
答案 0 :(得分:3)
这不是enums的用途。请改用一个班级。这是一个简单的例子:
public class ErrorCode
{
public static readonly ErrorCode COMMONS_DB_APP_LEVEL = new ErrorCode("Application problem: {0}", "Cause of the problem");
public static readonly ErrorCode COMMONS_DB_LOW_LEVEL = new ErrorCode("Low level problem: {0}", "Cause of the problem");
public static readonly ErrorCode COMMONS_DB_CONFIGURATION_PROBLEM = new ErrorCode("Configuration problem: {0}", "Cause of the problem");
private String message;
private String[] argumentDescriptions;
private ErrorCode(String message, params String[] argumentDescriptions)
{
this.message = message;
this.argumentDescriptions = argumentDescriptions;
}
public String[] GetArgumentDescriptions()
{
return argumentDescriptions;
}
public String GetKey()
{
// Need to implement this yourself
}
public String GetMessage()
{
return message;
}
}
Console.WriteLine(ErrorCode.COMMONS_DB_APP_LEVEL.GetMessage(), "Foo");
// Application problem: Foo
还有一些建议:
COMMONS_DB_APP_LEVEL
之类的名称不符合Microsoft的General Naming Conventions。GetMessage
等方法(除非您的方法需要很长时间才能执行或涉及副作用)。GetArgumentDescriptions
返回数组,因为它允许其他代码直接设置数组的任何元素(即使它们不能直接分配新数组)。考虑使用类似Array.AsReadOnly
的内容。答案 1 :(得分:1)
您只需使用该类并在类中创建枚举,并且如果您想要每个枚举值,也可以使用该描述。
public class ErrorCode
{
public enum ErrorCode
{
[Description("Application level problem")]
COMMONS_DB_APP_LEVEL,
[Description("Database level problem")]
COMMONS_DB_LOW_LEVEL,
[Description("Configuration level problem")]
COMMONS_DB_CONFIGURATION_PROBLEM
}
private String message;
private String[] argumentDescriptions;
private ErrorCode(String message, String[] argumentDescriptions)
{
this.message = message;
this.argumentDescriptions = argumentDescriptions;
}
public String[] GetArgumentDescriptions()
{
return argumentDescriptions;
}
public String GetKey()
{
return argumentDescriptions();
}
public String GetMessage()
{
return message;
}
}
答案 2 :(得分:-2)
因为您必须使用类而不是枚举来编写类似的代码。如果您有更多关于枚举的信息,可以访问this链接。