我有一个名为ClientCreditResolutionPlanActionType的SQL 查询表,我想将其转换为枚举在c#中。
非常基本的请求,对吧? 对。
现在我的表已经成为枚举, 然而它有几个列或者说是一些描述属性需要与之相关:
- StatusIcon
- StatusText
- TypeText
所以我想我可以做...
namespace System.ComponentModel
{
class StatusIconAttribute : Attribute
{
public string StatusIcon;
public StatusIconAttribute(string statusIcon) { StatusIcon = statusIcon; }
}
class StatusTextAttribute : Attribute
{
public string StatusText;
public StatusTextAttribute(string statusText) { StatusText = statusText; }
}
class TypeTextAttribute : Attribute
{
public string TypeText;
public TypeTextAttribute(string typeText) { TypeText = typeText; }
}
}
... 在我的 Extensions.cs 类中 ...
public static class EnumExtensions
{
public static string GetStatusIcon(this Enum value)
{
var type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null) { return null; }
var field = type.GetField(name);
if (field == null) { return null; }
var attr = Attribute.GetCustomAttribute(field, typeof(StatusIconAttribute)) as StatusIconAttribute;
if (attr == null) { return null; }
return attr.StatusIcon;
}
public static string GetStatusText(this Enum value)
{
var type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null) { return null; }
var field = type.GetField(name);
if (field == null) { return null; }
var attr = Attribute.GetCustomAttribute(field, typeof(StatusTextAttribute)) as StatusTextAttribute;
if (attr == null) { return null; }
return attr.StatusText;
}
public static string GetTypeText(this Enum value)
{
var type = value.GetType();
string name = Enum.GetName(type, value);
var type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null) { return null; }
var field = type.GetField(name);
if (field == null) { return null; }
var attr = Attribute.GetCustomAttribute(field, typeof(TypeTextAttribute)) as TypeTextAttribute;
if (attr == null) { return null; }
return attr.TypeText;
}
}
...最后在我的另一个项目中像这样使用它:
namespace ClientSystemServiceLibrary.Enums
{
[DataContract]
public enum ClientCreditResolutionPlanActionType
{
[EnumMember]
[TypeText("New resolution plan submitted.")]
[StatusText("New Plan")]
[StatusIcon("star.png")]
NewPlan = 1,
[EnumMember]
[TypeText("Resolution plan waiting on approval.")]
[StatusText("Under Review")]
[StatusIcon("review.png")]
UnderReview = 2,
[EnumMember]
[TypeText("Resolution plan approved.")]
[StatusText("Approved")]
[StatusIcon("check.png")]
Approved = 3,
[EnumMember]
[TypeText("Resolution plan rejected.")]
[StatusText("Rejected")]
[StatusIcon("cross.png")]
Rejected = 4,
[EnumMember]
[TypeText("New resolution plan comment submitted.")]
[StatusText("New Comment")]
[StatusIcon("message.png")]
NewComment = 5
}
}E
除此之外,我所想的都是错误的,因为我收到了这些错误信息:
'System.CompenentModel.TypeTextAttribute' 因其保护级别而无法访问。
以及
找不到类型或命名空间名称'TypeText'(您是否缺少 using 指令或程序集引用?)
对于所有三个相同的错误。