在属性中输入约束(Type constraints in Attributes)

编程入门 行业动态 更新时间:2024-10-28 11:28:09
属性中输入约束(Type constraints in Attributes)

我想用自定义属性编写我的枚举,例如:

public enum SomeEnum: long { [SomeAttribute<MyClass1>] Sms = 1, [SomeAttribute<MyClass2>] Email = 2 }

但属性不支持泛型。 那么,最类似的解决方案是:

public enum SomeEnum: long { [SomeAttribute(typeof(MyClass1))] Sms = 1, [SomeAttribute(typeof(MyClass2))] Email = 2 }

这里是问题:我想要Class1从ICustomInterface继承,所以对于泛型我可以写约束:

[AttributeUsage(AttributeTargets.All)] class SomeAttribute<T> : Attribute where T: ICustomInterface { }

但属性不支持泛型。

所以最后的问题是:如何在编译时检查(如T约束)该类型是否正在实现一些接口?

I want to write my enum with custom attributes, for example:

public enum SomeEnum: long { [SomeAttribute<MyClass1>] Sms = 1, [SomeAttribute<MyClass2>] Email = 2 }

but attributes doesn't support generics. Well, the most similar solution is:

public enum SomeEnum: long { [SomeAttribute(typeof(MyClass1))] Sms = 1, [SomeAttribute(typeof(MyClass2))] Email = 2 }

And here is problem: I want Class1 to be inherited from ICustomInterface, so with generics I can write constraint:

[AttributeUsage(AttributeTargets.All)] class SomeAttribute<T> : Attribute where T: ICustomInterface { }

but attributes doesn't support generics.

so finally question is: how can I check in compile time (like T constraints) that type is implementing some interface?

最满意答案

对你最后的问题很简单:

所以最后的问题是:如何在编译时检查(如T约束)该类型是否正在实现一些接口?

你不能这样做。

但是你可以在运行时检查它,使用一些反射方法: Type.IsAssignableFrom

Very simple to your final question:

so finally question is: how can I check in compile time (like T constraints) that type is implementing some interface?

You can not do that.

But you can check it at runtime, with some reflection methods like: Type.IsAssignableFrom

更多推荐

本文发布于:2023-07-30 13:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1337863.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   Type   Attributes   constraints

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!