CLSCompliance测试(或任何属性测试)

本文关键字:测试 属性 任何 CLSCompliance | 更新日期: 2023-09-27 18:20:49

下面是我定义的枚举的代码片段:

public enum DataTypes
{
    /// <summary>
    /// Base class.
    /// </summary>
    Object = 0,
    /// <summary>
    /// True / false.
    /// </summary>
    Boolean = 1,
    /// <summary>
    /// Signed 8 bit integer.
    /// </summary>
    [CLSCompliant(false)]
    Int8 = 2,

如何测试项目是否符合CLSCompliant真/假?

CLSCompliance测试(或任何属性测试)

如何测试项目是否符合CLSCompliant真/假?

使用Type.GetField获得相关的FieldInfo,然后使用MemberInfo.IsDefined

样本代码:

using System;
using System.ComponentModel;
using System.Globalization;
public enum DemoEnum
{
    Foo,
    Bar,
    [Description("This is a baz")]
    Baz
}
class Test
{
    static void Main()
    {
        foreach (var name in Enum.GetNames(typeof(DemoEnum)))
        {
            var field = typeof(DemoEnum).GetField(name);
            Console.WriteLine("{0}: {1}", name,
                              field.IsDefined(typeof(DescriptionAttribute),
                                              false));
        }
    }
}

如果需要实际的属性值,则需要使用MemberInfo.GetCustomAttributes