Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

design patterns - How to decorate enum with attribute in c#

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

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

1 Reply

0 votes
by (71.8m points)

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);   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...