如何使用C#中后期绑定的组装得到一个枚举值 [英] How to get an enum value from an assembly using late binding in C#

查看:302
本文介绍了如何使用C#中后期绑定的组装得到一个枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这有时需要自动化控制Excel中的一个C#3.0 WinForms应用程序。这是正常的工作很好早期绑定,但我有一些问题,当人没有安装Excel,但仍想用我的应用程序除了Excel的一部分。后期绑定似乎是一个解决方案。迟绑定在C#3相当繁琐,但我没有做任何特别困难。我下面的 http://support.microsoft.com/kb/302902 作为首发,它的工作搞好。

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?

比如,我怎么能使用反射获得 Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows 的值,这样我可以用它的的InvokeMethod 通话?

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.

感谢

推荐答案

枚举值被视为字段,以便你可以使用方法 Type.GetField 获得通过反射枚举选项的值

The enum values are considered fields so you can use the method Type.GetField to obtain the value of an enumeration option through reflection.

一个浓缩例如:

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

这篇关于如何使用C#中后期绑定的组装得到一个枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆