c# - 允许依赖于 AttributeUsage 的 Attribute 构造函数
问题描述
我有一个可以应用于类或属性的属性。这个类确实有两个构造函数。一个接受类型,一个接受类型和字符串。
[AttributeUsage(
AttributeTargets.Property |
AttributeTargets.Class,
AllowMultiple = true)]
class DcProxyAttribute : Attribute{
public DcProxyAttribute(Type type){ /*...*/ }
public DcProxyAttribute(Type type, string str){ /*...*/ }
}
我可以像这样使用它
[DcProxy(typeof(SomeType)]
class MyClass {
[DcProxy(typeof(SomeType, "Hello World")]
public string SomeProperty { get; set;}
}
我想将其限制为这种用法。像这样使用它才有意义。
以下用法现在被认为是有效的,但它们不应该。
[DcProxy(typeof(SomeType, "Hello world")]
class MyClass {
[DcProxy(typeof(SomeType)]
public string SomeProperty { get; set;}
}
这可以做到吗?
我可以为它创建两个单独的类。一个DcProxyForClass
和一个DcProxyForProperty
。并像使用它一样
[DcProxyForClass(typeof(SomeType)]
class MyClass {
[DcProxyForProperty(typeof(SomeType, "Hello World")]
public string SomeProperty { get; set;}
}
但是这种方式会使代码的可读性降低,因为从语义上讲它们是一样的。
解决方案
不,你基本上不能这样做。
选项:
- 忍受它,如果使用了错误的重载,则在运行时引发异常
- 有两个单独的属性,每个属性一个(正如您已经建议的那样) - 大概使用一个通用的基本类型属性
- 忍受它,但编写一个代码分析器(Roslyn 等)来检测场景并在 IDE/build 中对其进行标记(可能与“1”结合使用)
推荐阅读
- javascript - 关闭它的父窗口时,事件侦听器不在弹出窗口上工作
- python - 浏览网页的最佳(最快)方法是什么?
- laravel - 如何根据字段值从表中获取前 10 行?
- linux - OpenVPN 客户端无法在 Windows 计算机上运行?
- c# - 无法将具有一对一关系的模型与 Entity Framework Core 映射
- c# - 尝试为自定义 POCO 的简单列表获取 HashCode
- java - 从 Spring Boot 重定向角度页面时出现 CORS 错误:预检中 Access-Control-Allow-Headers 不允许标头字段内容类型
- python - 合并共享一个单元格值的 Python 3 DataFrame 行,将另一个值放入逗号分隔的数组中
- css - 猫头鹰旋转木马最后会产生空白空间
- ruby-on-rails - Axios post 工作,Axios put 没有通过预加载请求