简体   繁体   中英

Using an Enum as an Attribute Argument

Here is the code I would like to use:

public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }

EnumHelper looks like:

[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type MyEnum { get; set; }
    public EnumHelper(Type enum)
    {
        MyEnum = enum;
    }
}

The error I get on EnumHelper(Days) is that "Enum Name not valid at this point". Am I doing something wrong, or can this not be done?

MORE INFO

I am trying to pass the Enum (Days), and randomly get back one of the values.

NEVERMIND: I was over-complicating this part.

You're trying to pass a type name as if it were an argument value . You can't do that. However, you can do:

[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type EnumType;
    public EnumHelper(Type enumType)
    {
        EnumType = enumType;
    }
}

...

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }

However:

  • I wouldn't personally make EnumType a public field; make it a property.
  • There's currently no validation that EnumType is actually an enum. You can't do it at compile-time, but you could do it at execution time.
  • For the sake of convention, it should be called EnumHelperAttribute (or something more descriptive, really) - this isn't causing the error, but it's more idiomatic
  • I'm not really sure I see the benefit... you can find the type of the property from the metadata already; what do you think the attribute is actually buying you?

If you could let us know what you're trying to accomplish, we may be able to be more useful to you.

The parameters in Attributes can be only constants. If you want pass the enum type you must pass only the type:

[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }


[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
    public Type MyEnum;
    public EnumHelper(Type enum)
    {
        MyEnum = enum;
    }
}

参数应该是枚举值,而不是枚举类型,例如:

[EnumHelper(Days.Sat)]

Just wanted to add how I ran into this and fixed it. I had my property named the same as my enumeration. The code would compile and run, but I was getting a the red line error message in the IDE. Changing the name of the property to something unique cleared the message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM