Type constraints in Attributes

*爱你&永不变心* 提交于 2020-01-24 03:20:08

问题


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?


回答1:


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




回答2:


While i've had similar problems you won't get compile time checking for this.

For now this:

public class SomeAttribute : Attribute
{
    public SomeAttribute(Type given)
    {
        Given = given;
        Required = typeof (INotifyDataErrorInfo);
    }

    public Type Given { get; set; }
    public Type Required { get; set; }

    public bool Valid()
    {
        return Required.IsAssignableFrom(Given);
    }
}

public enum TestEnum 
{
    [Some(typeof(string))]
    Sms = 1,
    [Some(typeof(string))]
    Email = 2
}

Is far as you're gonna get sadly.

Though as far as i can recall, if you use PostSharp there is a way to invoke code dependant compile time checks if that's what you're after. That may not point out flaws visually in your IDE, but it still ensures that other devs have to ensure that a certain type is passed.



来源:https://stackoverflow.com/questions/26521670/type-constraints-in-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!