【发布时间】:2020-07-19 02:26:35
【问题描述】:
网上有很多创建枚举扩展方法的例子,该方法将枚举值作为参数,并在方法中获取特定属性,如下所示:
namespace MVVMProj.ProjUtilities
{
public class EnumerationHelpers
{
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;
}
}
}
我想知道的是,有没有办法也将属性类型传递给方法,所以我不需要为每个不同的属性编写特定的方法?
这还没有完成,但是,它应该让您了解我想要实现的目标:
namespace MVVMProj.ProjUtilities
{
public class EnumerationHelpers
{
public static string GetCustomAttribute(this Enum value, Type customAttr)
//Or instead of passing a Type, a string of the attribute's name
{
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, ....) as ....;
if (attr == null) { return null; }
return attr....;
}
}
}
我想我也不能只返回一个字符串,因为它可以是任何数据类型。
可能是一些通用方法?
任何建议将不胜感激!
编辑:用法:
它遍历枚举创建字典,以便我可以在组合框中显示值。仅当属性与 if 语句中的条件匹配时才添加项目。
还有一点需要注意的是,自定义属性也是一个枚举。
Aybe:“项目”只是迭代时的一个对象,所以我做了一个演员表。虽然我在 if 语句中遇到错误,但它试图将 CaseTypeAttribute 与实际的 CaseType 枚举值进行比较,我需要做些什么来解决?
错误:
严重性代码 描述 项目文件行抑制状态
错误 CS0019 运算符“==”不能应用于“SBC.CaseTypeAttribute”和“SBC.CaseType”类型的操作数
private Dictionary<int, string> _substancetypes;
public Dictionary<int, string> SubstanceTypes
{
get
{
if (_substancetypes == null)
{
_substancetypes = new Dictionary<int, string>();
foreach (var item in Enum.GetValues(typeof(SBC.SubstanceTypeCode)))
{
var descriptionAttribute = ((SBC.SubstanceTypeCode)item).GetAttribute<SBC.CaseTypeAttribute>();
if (descriptionAttribute != null &&
descriptionAttribute == SBC.CaseType.Exposures) //Error here
{
_substancetypes.Add((int)item, CTS_MVVM.CTS_Utilities.EnumerationHelpers.GetDescriptionFromEnumValue((SBC.SubstanceTypeCode)item));
}
}
}
return _substancetypes;
}
}
【问题讨论】:
标签: c# enums custom-attributes