我想用自定义属性编写我的枚举,例如:
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
更多推荐
发布评论