以编程方式获取 case 语句中常量的值
我需要一种方法来知道 case 语句中使用的常量的值。这可能吗? 例如
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
}
我到达的最远的地方是这个 http://www.csharp-examples.net/reflection-calling-method-名称/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,您需要传递该值。或者在共享外部作用域中使用变量(来自 Cameron)
No, you will need to pass the value. Or use a variable in a shared outer scope (From Cameron)
您需要像使用反射一样复杂吗?您可以只将常量的值存储在某个成员变量中以便在 mycallback() 方法中访问吗?例如:
请注意,这是未经测试的。
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:
Note this is untested.
在这种情况下,您必须使用“if”、“else if”语句。这不能通过 switch-case 语句来完成。
This is a case where you have to use "if", "else if" statements. This cannot be done with switch-case statements.