我刚刚为处理这个问题创建了这个工具类:
public static class EnumUtils
{
public static bool IsObsolete<TEnumType>(TEnumType value) where TEnumType : struct
{
var fi = value.GetType().GetField(value.ToString());
var attributes = (ObsoleteAttribute[])
fi.GetCustomAttributes(typeof(ObsoleteAttribute), false);
return (attributes != null && attributes.Length > 0);
}
public static List<TEnumType> GetObsoleteValues<TEnumType>() where TEnumType : struct
{
return GetAllValues<TEnumType>().Where(e => IsObsolete(e)).ToList();
}
public static List<TEnumType> GetNonObsoleteValues<TEnumType>() where TEnumType : struct
{
return GetAllValues<TEnumType>().Where(e => !IsObsolete(e)).ToList();
}
public static List<TEnumType> GetAllValues<TEnumType>() where TEnumType : struct
{
return Enum.GetValues(typeof(TEnumType)).Cast<TEnumType>().ToList();
}
}
对应的单元测试(MSTest)如下:
[TestClass]
public class EnumUtilsTest : UnitTestBase
{
#pragma warning disable CS0612 // Type or member is obsolete
[TestMethod]
public void GetAllValues_Test()
{
var values = EnumUtils.GetAllValues<UnitTestEnumValues>();
Assert.AreEqual(4, values.Count);
Assert.AreEqual(UnitTestEnumValues.A, values[0]);
Assert.AreEqual(UnitTestEnumValues.B_Obsolete, values[1]);
Assert.AreEqual(UnitTestEnumValues.C, values[2]);
Assert.AreEqual(UnitTestEnumValues.D_Obsolete, values[3]);
}
[TestMethod]
public void GetObsoleteValues_Test()
{
var values = EnumUtils.GetObsoleteValues<UnitTestEnumValues>();
Assert.AreEqual(2, values.Count);
Assert.AreEqual(UnitTestEnumValues.B_Obsolete, values[0]);
Assert.AreEqual(UnitTestEnumValues.D_Obsolete, values[1]);
}
[TestMethod]
public void GetNonObsoleteValues_Test()
{
var values = EnumUtils.GetNonObsoleteValues<UnitTestEnumValues>();
Assert.AreEqual(2, values.Count);
Assert.AreEqual(UnitTestEnumValues.A, values[0]);
Assert.AreEqual(UnitTestEnumValues.C, values[1]);
}
[TestMethod]
public void IsObsolete_Test()
{
Assert.AreEqual(false, EnumUtils.IsObsolete(UnitTestEnumValues.A));
Assert.AreEqual(true, EnumUtils.IsObsolete(UnitTestEnumValues.B_Obsolete));
Assert.AreEqual(false, EnumUtils.IsObsolete(UnitTestEnumValues.C));
Assert.AreEqual(true, EnumUtils.IsObsolete(UnitTestEnumValues.D_Obsolete));
}
public enum UnitTestEnumValues
{
A,
[Obsolete]
B_Obsolete,
C,
[Obsolete]
D_Obsolete
}
#pragma warning restore CS0612 // Type or member is obsolete
}