在线上有很多示例,这些示例创建一个枚举扩展方法,该方法以枚举值作为参数,并且在该方法中获取特定属性,例如:
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语句中的条件匹配时,才添加项目。
还有一点要注意的是,custom属性也是一个枚举。
Aybe:“ item”只是迭代中的一个对象,因此我进行了强制转换。尽管我在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;
}
}
像这样吗
using System;
using System.ComponentModel;
using System.Reflection;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
var descriptionAttribute = MyEnum.A.GetAttribute<DescriptionAttribute>();
}
}
public static class EnumExtensions
{
public static T GetAttribute<T>(this Enum @enum) where T : Attribute
{
var type = @enum.GetType();
var name = Enum.GetName(type, @enum);
var field = type.GetField(name);
var attribute = field.GetCustomAttribute<T>();
return attribute;
}
}
public enum MyEnum
{
[Description("A")] A,
[Description("B")] B
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句