Attribute Type Constraints

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

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

but attributes do not support generics. In the best way, the most similar solution:

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

And here is the problem: I want to Class1inherit from ICustomInterface, so in generics I can write a restriction:

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

but attributes do not support generics.

so finally the question is: how can I check compilation time (e.g. Tconstraints) that the type implements some interface?

+4
source share
2 answers

Very simple to your last question:

, , : (, T ), ?

.

, : Type.IsAssignableFrom

+4

, .

:

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
}

.

, , PostSharp, , , . IDE, - , .

0

All Articles