C# 枚举中的构造函数和方法
我想知道是否有办法在C#中的C# 枚举中的构造函数和方法,c#,enums,C#,Enums,我想知道是否有办法在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_PROBL
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
。我怎样才能做到这一点呢?枚举不是用于此目的的。改为使用类。下面是一个简单的例子:
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\u DB\u APP\u LEVEL
- 您通常应该使用而不是像
这样的方法(除非您的方法需要很长时间才能执行或涉及副作用)GetMessage
- 从
返回数组时应该小心,因为它允许其他代码直接设置数组的任何元素(即使它们不能直接分配新数组)。考虑使用类似的.GetArgumentDescriptions
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;
}
}
因为您必须使用类而不是枚举来编写类似的代码。如果你想了解更多枚举信息,可以访问链接。你可以创建一个
类。
…这篇文章缺少这么多信息!你到底想达到什么目的?