仅针对特定类的自定义属性

发布于 2024-08-21 00:37:11 字数 865 浏览 5 评论 0原文

我想对我的自定义 (PostSharp) 属性定义一个约束。我的目标是在编译时获得错误或警告,如果类 X 没有实现 Y 接口,但它具有我的属性。

所以这应该可行:

[MyAttributeOnlyForY]
public class X : Y { ... }

但这应该会破坏编译过程:

[MyAttributeOnlyForY]
public class X { ... }

这怎么可能?

原因

该属性的作用类似于一个方面(这是 PostSharp 属性),并且我想确保编织类提供了该属性所需的所有信息。

我想避免 null 结果,

(eventArgs.Instance as ILoggerServiceOwner)

并且我认为编译时间检查是一个很好的做法。

解决方案

我在这里找到了一个完美的开始:使用 PostSharp 方面验证属性使用

I would like to define a constrait on my custom (PostSharp) attribute. My goal is to get error or warning while compile time, if class X dont implements Y interface but it has my attribute.

So this should work:

[MyAttributeOnlyForY]
public class X : Y { ... }

but this should break the compile process:

[MyAttributeOnlyForY]
public class X { ... }

How is it possible?

The reason

This attribute works like an aspect (this is PostSharp attribute), and I want to be sure that the weaved class provides all needed information for this attribute.

I want to avoid null result on

(eventArgs.Instance as ILoggerServiceOwner)

and I think complie time checking is a good practice.

Solution

I've found a perfect start here: Validating attribute usage with PostSharp Aspects

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戒ㄋ 2024-08-28 00:37:11

您可以使用 PostSharp 方法 CompileTimeValidate 并使用反射来检查类型是否具有派生类型。但是,查找程序集中的所有类型可能会耗费大量计算资源。

You could use the PostSharp method CompileTimeValidate and use reflection to check if type has a derived type. However, it may be computationally expensive do look for all types in the assembly.

半仙 2024-08-28 00:37:11

我认为这是不可能的。
更好的解决方案可能是在自定义属性构造函数上使用 Obsolete 属性来警告目标类应实现接口 Y。

I think this is not possible.
A better solution might be to use the Obsolete attribute on your custom attribute constructor to warn that the target class should implement the interface Y.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文