简体   繁体   中英

Get Variables in struct by name

I want to get the value from variables in a struct using the name of the variables in the struct. A function should use a string to return the value of the variable with this name in a struct.

In this Example the "GetStingfromStruct" function should return "asdf". (The current Code is just some testing and returns "System.String string1").

If this problem is solved, I have another question. Is there a way to check if the struct contains a variable with the name of the string. (To avoid Errors)

private void SetStruct()
{
    Mystruct mystruct = new Mystruct();
    mystruct.string1="asdf";
    mystruct.string2="ghjkl";
    mystruct.string3="qwert";
}

private sting GetStingfromStruct(string variableName)
{
    return mystruct.GetType().GetField("string1")
}

public struct Mystruct
{
    public string string1;
    public string string2;
    public string string3;
}

You are declaring an instance of struct inside set struct method, which you are then trying to access in a get struct method which has no access to said instance. This will not work. Why are you trying to use getters and setters for this struct? Why are you trying to use a struct when you could use a dictionary?

A dictionary could be used as follows:

var myDict = new Dictionary<string, string>
{
    { "key1", "value1" },
    { "key2", "value2" }
};

You can use reflection :

In general case , for an arbitrary struct and arbitrary field you can put

    using System.Linq;
    using System.Reflection;

    ...

    // returns field value by variableName
    // or null if field is not found
    private static string GetStringFromStruct<T>(T source, string variableName) 
      where T : struct =>
        typeof(T)
          .GetFields(BindingFlags.NonPublic | BindingFlags.Public | 
                     BindingFlags.Instance | BindingFlags.Static)
          .Where(field => field.Name == variableName)
          .Select(field => field.GetValue(field.IsStatic ? null : source))
          .FirstOrDefault() 
         ?.ToString();

Then you can use it as

string result = GetStringFromStruct(mystruct, "string1");

If you want to inspect mystruct only, and don't want to use Dictionary<string, string> instead:

private sting GetStringfromStruct(string variableName)
{
    var field = mystruct.GetType().GetField(variableName);

    if (field == null)
      return null; // variableName has not found

    return field.GetValue(mystruct)?.ToString(); 
}

The minimum change to make is to pass the instance ( mystruct ) to the GetValue method:

private sting GetStingfromStruct(string variableName)
{
    return (string)mystruct.GetType().GetField(variableName).GetValue(mystruct);
}

You should also add checks to make sure the string value is actually a field name, etc.

But I would echo other comments and answers that this is not a great design unless you're forced to use a struct for some reason.

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