【问题标题】:Testing for CLSCompliance (or testing for any attribute)测试 CLSCompliance(或测试任何属性)
【发布时间】:2013-07-03 15:23:19
【问题描述】:

这是我定义的枚举的代码 sn-p:

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 真/假?

【问题讨论】:

标签: c# c#-4.0 attributes custom-attributes


【解决方案1】:

我如何测试一个项目的 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

【讨论】:

  • 感谢 Jon :) 我对此进行了调整,使用 Enum.GetName() 直接获取我想要的,并且效果很好。必须使用字符串名称来获取它,而不是传递 (int) 枚举类型,这似乎有点繁重,但我想这是因为它也对方法进行操作。
  • @IanC:好吧,您正在尝试获取 field - 在一个枚举中可能有多个具有相同值的字段。
猜你喜欢
  • 2019-04-07
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多