c# - 将属性约束为给定类型的属性

标签 c# constraints custom-attributes

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

例如:

[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!" ;
}

如果我可以限制我的属性,以便它们只能在实现特定接口(interface)(或继承特定基类)的类中使用,那就太好了。

最佳答案

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

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

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

关于c# - 将属性约束为给定类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803105/

相关文章:

ASP.NET MVC2 不在 HtmlAttributes 中用破折号替换下划线

c# - 用于解析 C/C++ 函数声明的正则表达式

C#单元测试代码题

c# - 是否存在将我的泛型方法限制为数字类型的约束?

generics - F# - 类型参数在 'k : comparison 时缺少约束

ios - 以编程方式为 iPhone 和 iPad 布局 UI 的最佳实践

c# - 同步异常

c# - 从 HttpResponseMessage.Content 读取流式内容

.net - 缺少自定义属性时选择正确的异常类型

c# - 如何从自定义属性中确定附加类型?