C# 使用变量调用另一个变量

C# 使用变量调用另一个变量,c#,php,c#-4.0,unity3d,C#,Php,C# 4.0,Unity3d,所以我是C#的新手,我需要知道我想做的事情是否可能,以及我所拥有的是什么 public static class Sempre { public static string Raca = ""; } // Sempre.Raca - can use like this 现在我要做的是设置一个变量,比如thing=“example”,在调用Sempre之后,使用变量,比如,Sempre.thing,但因为它是一个变量,所以实际上是Sempre.example 我希望在php中使

所以我是C#的新手,我需要知道我想做的事情是否可能,以及我所拥有的是什么

public static class Sempre
{    
    public static string Raca = "";
}

// Sempre.Raca - can use like this
现在我要做的是设置一个变量,比如
thing=“example”
,在调用Sempre之后,使用变量,比如,
Sempre.thing
,但因为它是一个变量,所以实际上是Sempre.example

我希望在php中使用相同的示例

$example = mean;
$_SESSION['name'.$example];

would create $_SESSION [namemean];

您可以使用索引器设置您的类型。要使用索引器,您需要有一个实例类而不是静态类。如果确实需要,可以使用来获得“静态”行为

以下是使用索引器的示例:

public class Sempre
{
    private Dictionary<string, string> _values = new Dictionary<string, string>();

    public string this[string key]
    {
        get { return _values[key]; }
        set { _values[key] = value; }
    }
}

一般来说,您不能在C#中对对象执行此操作,因为代码是在运行时之前预编译的

如果您正在寻找http会话状态的实现,就像您在PHP代码示例中所做的那样,那么可以这样做。会话状态在System.Web.SessionState.HttpSessionState中公开,可以通过连接字符串访问,如示例中所示

String example = "mean";
Session["name" + example] = 'bar';
//Session["namemean"] is now set to value of 'bar'

如果您只希望进行字符串替换,还可以执行以下操作:

Sempre sempre = new Sempre();

sempre["example"] = "my value";

string thing = "example";

Console.WriteLine(sempre[thing]);
public class StringConstants
{
    public static string YES = "yes";
    public static string NO = "no";
}
然后在别处

public void printmessage(bool value)
{ 
    if (value)
    {
    Console.writeline (string.Format "I Say {0}", StringConstants.YES);
    }
    else
    {
     Console.writeline (string.Format "I Say {0}", StringConstants.NO);
    } 
}

关于字符串的文档。插入和组合的格式为

检查有关键入的回答