属性中的类型约束 [英] Type constraints in Attributes

查看:118
本文介绍了属性中的类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

这是问题:我想从 ICustomInterface <继承 Class1 / code>,因此可以使用泛型写约束:

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
{
}

但属性没有支持泛型。

所以最后一个问题是:如何检查该类型的编译时间(如 T 约束)

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

推荐答案

对最后一个问题很简单:

Very simple to your final question:

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

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

您不能这样做。

但是您可以在运行时使用一些反射方法来检查它,例如:
< a href = http://msdn.microsoft.com/de-de/library/system.type.isassignablefrom(v=vs.110).aspx rel = noreferrer> Type.IsAssignableFrom

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

这篇关于属性中的类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆