简体   繁体   中英

get a string value from its name

I have a string name given to me in a string.

Like this:

string myawesomestring = "hey";
string mystringname = "myawesomestring";

I need to get myawesomestring value but the myawesomestring can change.

I hope you get what I mean, if you don't comment I will fix it myself.

Something like this?

string mystringname += myawesomestring;

I understand that you want to read the value of a string by some kind of string value stored in another variable (which is dynamic). I don't think this can be achieved with just simple string data type, but you can do this by using some complex data types like dictionary or class or something similar.

First solution might be storing the data in a dictionary, but you have to make sure the keys are unique. Eg

string mystringname1 = "MyAwesomeString1";
string mystringname2 = "MyAwesomeString2";

var awesomeStrings = new Dictionary<string, string>
{
    {"MyAwesomeString1","hey1" },
    {"MyAwesomeString2","hey2" }
};

string vaule1 = awesomeStrings[mystringname1];
string vaule2 = awesomeStrings[mystringname2];

If you have more attributes, then you can create a class and with the use of little bit of reflection, you can easily read the property values. Eg

public class AwesomeString
{
    public string MyAwesomeString1 { get; set; } = "hey1";
    public string MyAwesomeString2 { get; set; } = "hey2";
}

class Program
{
    static void Main(string[] args)
    {
        string mystringname1 = "MyAwesomeString1";
        string mystringname2 = "MyAwesomeString2";

        AwesomeString awesomeString = new AwesomeString();

        string vaule1 = (string)awesomeString.GetType().GetProperty(mystringname1).GetValue(awesomeString);
        string vaule2 = (string)awesomeString.GetType().GetProperty(mystringname2).GetValue(awesomeString);
        /* ... */
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM