【问题标题】:Constraint Attribute to property of given type将属性约束到给定类型的属性
【发布时间】:2016-11-25 10:44:14
【问题描述】:

如标题中所述,我想知道是否有一种方法来约束属性,以便在将属性应用于错误的属性或方法时出现编译时错误(我希望这些属性将适用仅限于财产)。

例如:

[StringAttribute(..something)]
public string  MyStringPropery { get; set; } //<-- ok pass compile time constraint

[StringAttribute(..something)]
public int MyIntProperty { get; set; } //<-- throw error at compile time for type missmatch (that attribute will apply only to string not int)

[StringAttribute(..something)]
public string SayHello ()  //<-- throw error at compile time, that attribute apply only to property not method
{
    return "Hello!" ;
}

如果我可以约束我的属性,这样它们只能在实现特定接口(或从特定基类继承)的类中使用,那将是很好的选择。

【问题讨论】:

    标签: c# constraints custom-attributes


    【解决方案1】:

    无法在编译时检查属性的类型,因为您无权访问您附加属性的成员。此外,编译器实际上不会实例化您的属性或在其上运行代码。它只会将其添加到程序集元数据中。编译器运行其内置检查,您无法扩展。

    但可以在属性定义中限制属性:

    [AttributeUsage(AttributeTargets.Property)]
    public class StringAttribute : Attribute
    {
        //Attribute definition
    }
    

    【讨论】:

    • @Safe 谢谢这限制了我的问题。对于类型检查,我将使用运行时检查来更改方法,而不是尝试在编译时进行检查。据您所知,有一种方法可以约束将使用我的属性的类?
    • 你的意思是例如具有特定名称的类?恐怕这也不可能。
    • 不,我没有一个实现某个接口的类,例如:IConfigurable(我的自定义接口)或从某个基类继承
    • 正如我所说,您无权访问该属性所附加到的类。因此,您无法进行此检查。
    猜你喜欢
    • 2014-12-18
    • 2021-01-30
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多