How to get an enum value from an assembly using late binding in C#
I have a C# 3.0 WinForms application which is occasionally required to control Excel with automation. This is working nicely with normal early binding but I've had some problems when people don't have Excel installed but still want to use my app except for the Excel part. Late binding seems to be a solution to this. Late binding is rather tedious in C# 3 but I'm not doing anything particularly difficult. I'm following http://support.microsoft.com/kb/302902 as a starter and it's working out well.
My question is how can I use开发者_开发技巧 an enum by name?
e.g, how can I use reflection to get the value of Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows
so that I can use it an InvokeMethod
call?
I know the easiest way is probably to create my own local enum with the same "magic" integer value but it would be nicer to be able to access it by name. The docs often don't list the value so to get it I probably need to have a little early bound test app that can tell me the value.
Thanks
The enum values are considered fields so you can use the method Type.GetField
to obtain the value of an enumeration option through reflection.
A condensed example:
namespace ConsoleApp
{
enum Foo { Bar = 5 }
class Program
{
static void Main()
{
// Get the assembly containing the enum - Here it's the one executing
var assembly = Assembly.GetExecutingAssembly();
// Get the enum type
var enumType = assembly.GetType("ConsoleApp.Foo");
// Get the enum value
var enumBarValue = enumType.GetField("Bar").GetValue(null);
// Use the enum value
Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);
}
}
}
Outputs:
// Bar|5
Given the following example:
enum Test
{
Value1,
Value2
}
I can get a list of values and names like this:
foreach (var enumValue in typeof(Test).GetEnumValues())
{
string name = enumValue.ToString();
int value = (int) enumValue;
}
Would Enum.Parse help? For example
// given this enum
enum MyEnum
{
Value1,
Value2
}
// you can get the value via string
MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), "Value1");
精彩评论