2017-09-01 25 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); 
    }