c# - 可以在编译时评估 C# 自定义属性吗?

标签 c# .net metaprogramming custom-attributes

我有以下自定义属性:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
sealed public class CLSASafeAttribute : Attribute
{
    public Boolean CLSSafe { get; set; }
    public CLSASafeAttribute(Boolean safe)
    {
        CLSSafe = safe;
    }
}

以及以下部分枚举:

public enum BaseTypes
{
    /// <summary>
    /// Base class.
    /// </summary>
    [CLSASafe(true)]
    Object = 0,

    /// <summary>
    /// True / false.
    /// </summary>
    [CLSASafe(true)]
    Boolean,

    /// <summary>
    /// Signed 8 bit integer.
    /// </summary>
    [CLSASafe(false)]
    Int8
}

我现在希望能够为每个枚举创建一个唯一的类,并能够通过查看正在实现的类型将其标记为 CLSSafe。我有以下内容,这显然是不正确的,但说明了我的意图:

[CLSASafe((Boolean)typeof(BaseTypes.Object).GetCustomAttributes(typeof(BaseTypes.Object), false))]
sealed public class BaseObject : Field
{
    public Object Value;
}

有没有办法做到这一点(除了手动标记签名)?

最佳答案

我建议你定义你的属性如下:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
sealed public class CLSASafeAttribute : Attribute {
    public CLSASafeAttribute(Boolean safe) {
        CLSSafe = safe;
    }
    public CLSASafeAttribute(BaseTypes type) {
        CLSSafe = IsCLSSafe(type);
    }
    public Boolean CLSSafe {
        get;
        private set;
    }
    public static bool IsCLSSafe(BaseTypes type) {
        var fieldInfo = typeof(BaseTypes).GetField(typeof(BaseTypes).GetEnumName(type));
        var attributes = fieldInfo.GetCustomAttributes(typeof(CLSASafeAttribute), false);
        return (attributes.Length > 0) && ((CLSASafeAttribute)attributes[0]).CLSSafe;
    }
}

然后,就可以使用下面的声明:

class Foo {
    [CLSASafe(BaseTypes.Object)] // CLSSafe = true
    object someField1;
    [CLSASafe(BaseTypes.Boolean)] // CLSSafe = true
    bool someField2;
    [CLSASafe(BaseTypes.Int8)] // CLSSafe = false
    byte someField3;
}

或者,无论如何确定特定字段是否安全:

BaseTypes baseType = GetBaseType(...type of specific field ...);
bool isCLSSafe = CLSASafeAttribute.IsCLSSafe(baseType);

关于c# - 可以在编译时评估 C# 自定义属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840746/

相关文章:

c# - 使用 C# 扫描人机接口(interface)设备 (HID)

c# - 无法验证 DKIM 的正文哈希

c# - 字典到条件匹配的键列表

c# - 如何递归查询 Winform 的所有子控件?

python - 元编程 - 使用 __class__ 时如何从模板生成类?

c# - Autofac - 如何在创建实例时获取类名

c# - 序列化代码导致未处理的异常

c# - 从 MainWindow 访问类中的方法

Ruby - 将变量传递给 eval 方法

c++ - 元多运算符重载