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
623 views
in Technique[技术] by (71.8m points)

reflection - 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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

...