开发者

How to get a list of member names from Enum?

This should be fairly simple question. I'm using DocX library to create new word documents. I wanted to make a test word document to see how eac开发者_高级运维h TableDesign (enum) looks like to choose the one I need.

Designs\Styles that can be applied to a table. Namespace: Novacode Assembly: DocX (in DocX.dll) Version: 1.0.0.10 (1.0.0.10)

Syntax:

public enum TableDesign

Member name

Custom

TableNormal

TableGrid

LightShading

LightShadingAccent1

....

And so on. I would like to get a list of those TableDesign's so i could reuse it in a method creating new table with new design for all possibilities, but I don't really know how to get the list from that enum:

foreach (var test in TableDesign) {
      createTable(documentWord, test);
}

How do I get that?


Found answer myself:

// get a list of member names from Volume enum,
// figure out the numeric value, and display
foreach (string volume in Enum.GetNames(typeof(Volume)))
{
    var value = (byte)Enum.Parse(typeof(Volume), volume);
    Console.WriteLine("Volume Member: {0}\n Value: {1}", volume, value);
}

For my specific case I've used:

foreach (var test in Enum.GetNames(typeof(TableDesign)))
{
  testMethod(documentWord, test);
}

and in testMethod I've:

tableTest.Design = (TableDesign) Enum.Parse(typeof(TableDesign), test);

It worked without a problem (even if it was slow, but I just wanted to get things quickly (and being onetimer performance didn't matter).

Maybe it will help someone in future too :-)


Alternately:

foreach (var volume in Enum.GetValues(typeof(Volume))) 
{ 
    Console.WriteLine("Volume Member: {0}\n Value: {1}", 
        volume, (int) volume); 
} 

GetValue will return an Volume[] of the values as enums. Printing an enum value will call its ToString(), rendering it by it name. Casting to int (better than byte) will give its number.


I wanted to add a comment on MadBoy's answer, dont know why i cant...
anyway like he said thats the way to go

foreach (TableDesign t in Enum.GetNames(typeof(TableDesign)))
{
     // do work
}

also i think the testing could be like

bool defined = Enum.IsDefined(typeof(TableDesign), value);

it just seems more natural
last, about the performance issue, i think enums tend to be very small so i wont be worried at all

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜