Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an enum on helper library in my solution. For example

 public enum MyEnum 
 {  
  First,
   Second 
  }

I want to use MyEnum in a few another project. I want to decorate this enum in each project with own attribute like this:

public enum MyEnum 
 { 
 [MyAttribute(param)] 
 First,
 [MyAttribute(param2)]
 Second 
}

How to decorate enum from another library with own local attribute?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can't do what you've described - the best you can do is to create a new Enum that uses the same set of values. You will then need to cast to the "real" enum whenever you use it.

You could use T4 templates or similar to generate the attributed enum for you - it would be much safer that way as it would be very easy to map the wrong values, making for some very subtle bugs!

Linqpad Query

enum PrimaryColor
{
    Red,
    Blue,
    Green
}

enum AttributedPrimaryColor
{
    [MyAttribute]
    Red = PrimaryColor.Red,
    [MyAttribute]
    Blue = PrimaryColor.Blue,
    [MyAttribute]
    Green = PrimaryColor.Green
}

static void PrintColor(PrimaryColor color)
{
    Console.WriteLine(color);
}

void Main()
{
    // We have to perform a cast to PrimaryColor here.
    // As they both have the same base type (int in this case)
    // this cast will be fine.
    PrintColor((PrimaryColor)AttributedPrimaryColor.Red);   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...