开发者

programmatically get the value of the constant in a case statement

开发者 https://www.devze.com 2023-03-24 13:59 出处:网络
I need a way to know the value of the constant used in the case statement. Is this possible? For example

I need a way to know the value of the constant used in the case statement. Is this possible? For example

private void myswitchfunc(string myvar) {
    switch(myvar) {
        case "hello":
             mycallback();  //no variable passing!
             break;
        case "hi":
             mycallback();  //no variable passing!
             break;
    }
开发者_高级运维}
private void mycallback() {
        //print the name of the constant in the calling case 
}

The farthest I got to is this http://www.csharp-examples.net/reflection-calling-method-name/


No, you will need to pass the value. Or use a variable in a shared outer scope (From Cameron)


private static void myswitchfunc(string myvar)
{
    Action mycallback = () => Console.WriteLine(myvar);
    switch (myvar)
    {
        case "hello":
            mycallback();  //no variable passing!
            break;
        case "hi":
            mycallback();  //no variable passing!
            break;
    }
}


Do you need to get as complex as using Reflection? Can you just just store the value of the constant in some member variable to access in the mycallback() method? For example:

class MyClass
{
    private string _MySwitchString;

    private void myswitchfunc(string myvar) {
    _MySwitchString = myvar;
    switch(myvar) {
        case "hello":
             mycallback();  //no variable passing!
             break;
        case "hi":
             mycallback();  //no variable passing!
             break;
       }
   }
   private void mycallback() {
           //print the name of the constant in the calling case 
      Console.Writeline(_MySwitchString); 
   }
}

Note this is untested.


This is a case where you have to use "if", "else if" statements. This cannot be done with switch-case statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消