C#根据字符串更改我调用的方法

时间:2017-09-01 14:06:07

标签: c#

首先抱歉,如果这是重复的话。我不知道如何搜索这个。

我有一个问题,关于如何使用保存的字符串来更改我调用的方法类型

MenuBar.Dock = Dockstyle.DockStyleString //DockStyleString is a string defined somewhere with either Top or Bottom

2 个答案:

答案 0 :(得分:2)

因此,根据您的示例,您似乎正在使用枚举器。 Enum具有将字符串“转换”为正确的枚举值的实用程序。您也可以使用一个实用程序类来为您执行此操作。

DockstyleUtils.FromString("DockStyleString");

这将返回枚举Dockstyle.DockstyleString

因此,您可以使用它MenuBar.Dock = DockstyleUtils.FromString("DockStyleString");

我创建了这个你可以使用的方法......

public DockStyle ConvertDockingStyleFromString(string dockingStyle)
        {
            return (DockStyle)Enum.Parse(typeof(DockStyle), dockingStyle);
        }

你去。

答案 1 :(得分:0)

其中一些取决于你拥有它后要对字符串做什么。您可以使用@ PepitoFernandez的答案中的代码将其转换为枚举。如果您想使用它来确定针对对象调用哪种方法,您可以选择几种方法。

首先,如果它是一组已知的字符串,您可以使用switch语句:

switch (stringVariable) {
    case "stringA": methodA(); break;
    case "stringB": methodB(); break;
    ...
    // If you get a "bad" string, you WANT to throw an exception to make
    // debugging easier
    default: throw new ArgumentException("Method name not recognized");
}

显然,如果先进行转换,也可以用枚举值替换它。 (这实际上并不是一个坏主意,因为如果你得到一个“坏”字符串

另一个选项(如果你想在运行时动态完成)是使用反射进行调用,如下所示:

public class SomeClass
    {
        public void MethodA()
        {
            Console.WriteLine("MethodA");
        }
    }

    static void Main(string[] args)
    {
        Type type = typeof(SomeClass);
        // Obviously, you'll want to replace the hardcode with your string
        MethodInfo method = type.GetMethod("MethodA");

        SomeClass cls = new SomeClass();

        // The second argument is the parameters; I pass null here because
        // there aren't any in this case
        method.Invoke(cls, null);
    }
相关问题