我有一个 C# 3.0 WinForms 应用程序,偶尔需要它来自动控制 Excel。这与正常的早期绑定(bind)一起工作得很好,但是当人们没有安装 Excel 但仍然想使用我的应用程序时,我遇到了一些问题,除了 Excel 部分。后期绑定(bind)似乎是解决这个问题的方法。后期绑定(bind)在 C# 3 中相当乏味,但我没有做任何特别困难的事情。我正在关注 http://support.microsoft.com/kb/302902作为初学者,效果很好。
我的问题是如何按名称使用枚举?
例如,我如何使用反射获取 Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows
的值,以便我可以将它用于 InvokeMethod
调用?
我知道最简单的方法可能是使用相同的“神奇”整数值创建我自己的本地枚举,但如果能够通过名称访问它会更好。文档通常不会列出该值,因此要获得它,我可能需要一个可以告诉我该值的早期绑定(bind)测试应用程序。
谢谢
最佳答案
枚举值被视为字段,因此您可以使用方法 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);
}
}
}
输出:
// Bar|5
关于c# - 如何在 C# 中使用后期绑定(bind)从程序集中获取枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065526/