如何将枚举与dynamic和word一起使用



在这个函数中,我使用Word加载一个模板,并用其他单词替换某些单词。这并不重要。如何将函数更改为使用dynamic?特别是,如何在不引用Microsoft.Office.Interop.Word的情况下使用枚举(如WdReplace.wdReplaceOne)?

public static void CreateSheetByReplacement(String student, List<String> words)
{
    Application WordApp = new Application();
    WordApp.Documents.Add(Environment.CurrentDirectory + "\SpellingsReplace.dot");
    WordApp.Selection.Find.Execute(FindText: "studentname", Replace: WdReplace.wdReplaceOne, Wrap: WdFindWrap.wdFindContinue, ReplaceWith: student);
    for (int i = 0; i < 80; i++)
    {
        String word = (i < words.Count ? words[i] : "");
        WordApp.Selection.Find.Execute(FindText: "[word" + (i + 1) + "]", Replace: WdReplace.wdReplaceOne, Wrap: WdFindWrap.wdFindContinue, ReplaceWith: word);
    }
    WordApp.Visible = true;
    WordApp = null;
}

我只需要一个如何使用枚举的例子。

虽然除了直接使用各自的整数值之外,没有任何方法可以轻松地将枚举与dynamic后期绑定一起使用,但您可以使用一些反射和ExpandoObject来构建动态查找对象:

public static class DynamicInterop
{
    public static DynamicInterop()
    {
        var enumsDict = new ExpandoObject() as IDictionary<string, Object>;
        // Get all enum types from interop assembly
        var interopEnums = GetInteropAssembly()
            .GetTypes()
            .Where(type =>
                typeof(Enum).IsAssignableFrom(type));
        // For all enum types create a member in the enums dynamic object
        foreach (var type in interopEnums)
        {
            var curEnum = new ExpandoObject() as IDictionary<string, Object>;
            // Get Enum value name and values as KeyValuePairs
            var enumKeyValues = Enum
                .GetNames(type)
                .Zip(Enum.GetValues(type).Cast<Object>(), 
                    (key, value) =>
                        new KeyValuePair<String, Object>(key, value));
            // Create members for every enum value name-value pair
            foreach (var keyValue in enumKeyValues)
            {
                curEnum.Add(keyValue.Key, keyValue.Value);
            }
            enumsDict.Add(type.Name, curEnum);
        }
        DynamicInterop.Enums = enumsDict;
    }
    public static dynamic CreateWordApp()
    {
        throw new NotImplementedException();
    }
    public static dynamic Enums
    {
        get;
        private set;
    }
}

虽然这种方法可能不完全适合您的需求,但它至少会降低传递错误枚举值的概率。

附言:它没有经过测试,所以可能会有一些打字错误或其他错误。

p.S.1:尽管如此,如果没有Intellisense和其他IDE以及编译器的帮助,使用dynamic与Interop的后期绑定很容易成为代码中最难维护的部分。