2017-09-01 59 views
-4

首先抱歉,如果这是重复的。我不完全知道如何搜索这个。C#根据字符串更改我调用的方法

我有一个关于如何能够使用保存的字符串改变什么类型的方法我称之为

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

编写这样的代码,使用链式[if/else if/else](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else)语句,或者一个[switch语句](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch)。你必须自己编写这段代码,试一下,如果它没有'但我们不会为你写代码 –

+3

你的问题是不够的,请提供更多信息,详细说明wh在你期望能够做到的,以及你尝试过的代码不起作用的例子。 – Sam

+0

'if(menuBar.Dock ==“Bottom”)Dothis();其他DoSomeThingelse(); “由于您没有提供足够的信息,因此我们无能为力。所以你会得到的答案是模糊的。 – HimBromBeere

回答

2

这样的问题,根据您的例子中,你似乎可以用一个枚举。枚举具有将“转换”为正确枚举值的字符串的实用程序。你也可以有一个工具类来为你做。

DockstyleUtils.FromString("DockStyleString"); 

这将返回枚举Dockstyle.DockstyleString

所以,你可以用它MenuBar.Dock = DockstyleUtils.FromString("DockStyleString");

我创造了这个方法,你可以使用...

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

你去那里。

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); 
    }