如何在C#中使用后期绑定从程序集中获取枚举值

tet*_*anz 9 c# reflection

我有一个C#3.0 WinForms应用程序,偶尔需要通过自动化控制Excel.这与正常的早期绑定很好地工作,但是当人们没有安装Excel但仍想使用我的应用程序时,我有一些问题,除了Excel部分.后期绑定似乎是解决这个问题的方法.在C#3中,后期绑定相当繁琐,但我没有做任何特别困难的事情.我正在关注http://support.microsoft.com/kb/302902作为首发,它运作良好.

我的问题是如何按名称使用枚举?

例如,我如何使用反射来获取值,Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows以便我可以使用它进行InvokeMethod调用?

我知道最简单的方法可能是使用相同的"魔术"整数值创建我自己的本地枚举,但是能够通过名称访问它会更好.文档通常不会列出值,所以为了得到它我可能需要一个早期绑定测试应用程序,可以告诉我的价值.

谢谢

Joã*_*elo 15

枚举值被视为字段,因此您可以使用该方法Type.GetField通过反射获取枚举选项的值.

一个浓缩的例子:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

// Bar|5
Run Code Online (Sandbox Code Playgroud)