开发者

Custom attribute only on specific classes

开发者 https://www.devze.com 2022-12-20 03:43 出处:网络
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.

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 P开发者_StackOverflow社区ostSharp Aspects


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消