【问题标题】:How to access var by constructing name using variable and a string [duplicate]如何通过使用变量和字符串构造名称来访问var [重复]
【发布时间】:2018-08-28 11:03:28
【问题描述】:

在 PHP 中,您可以执行以下操作来访问变量:

$foobar1 = 00.00;
$foobar2 = 11.11;
$foobar3 = 22.22;
$i = 2;

echo ${'foobar' . $i}; //Prints 11.11

我想在 C# 中做同样的事情,但我似乎无法让它工作:

double foobar1 = 00.00;
double foobar2 = 11.11;
double foobar3 = 22.22;
int i = 2;

Print("foobar" + i); //Should print 11.11

有什么想法吗?我尝试了一些不同的搜索,但似乎找不到我要查找的内容。

干杯!

【问题讨论】:

  • 为什么需要它?如果所有变量的含义相似,则应将它们放在double[]List<double> 中。如果您确实需要从名称到值的映射,您可以使用Dictionary<string, double>

标签: c# dynamic-variables


【解决方案1】:

无法通过构造名称来动态引用变量。您可以对属性等使用反射。

我建议使用数组或列表:

double[] foobar = { 00.00, 11.11, 22.22 };
int i = 2 - 1; // arrays are 0-based

Print(foobar[i]); //Does print 11.11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2021-07-05
    相关资源
    最近更新 更多