使用变量调用另一个

时间:2014-06-16 20:58:46

标签: c# php c#-4.0 unity3d

所以我是C#的新人,我需要知道我想做什么是可能的,以及我的内容如何,​​

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

// Sempre.Raca - can use like this

现在我要做的是设置一个像thing = "example"之类的变量,在此之后调用Semper,但变量类似于Sempre.thing,但因为它是一个变量,它实际上是Sempre.example。

我想在php中使用相同的例子,

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

would create $_SESSION [namemean];

3 个答案:

答案 0 :(得分:0)

您可以使用索引器设置类型。 http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx。要使用索引器,您需要具有实例类而不是静态类。如果你真的需要,你可以使用singleton pattern获得"静态"行为。

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

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; }
    }
}

你可以像这样使用它:

Sempre sempre = new Sempre();

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

string thing = "example";

Console.WriteLine(sempre[thing]);

答案 1 :(得分:0)

一般来说,你不能用C#中的对象来做这件事,因为代码是在运行之前预编译的。

如果您专门寻找http会话状态的实现,就像在PHP代码示例中那样,那么就可以完成。会话状态在System.Web.SessionState.HttpSessionState中公开,可以通过类似于此示例的连接字符串进行访问。

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

答案 2 :(得分:0)

如果你只想做字符串替换,你也可以这样做:

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);
    } 
}

有关插入和合成的string.Format的文档是here