简体   繁体   English

按名称获取结构中的变量

[英]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. function 应该使用字符串来返回结构中具有此名称的变量的值。

In this Example the "GetStingfromStruct" function should return "asdf".在此示例中,“GetStingfromStruct”function 应返回“asdf”。 (The current Code is just some testing and returns "System.String string1"). (当前代码只是一些测试并返回“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.您在 set struct 方法中声明了一个 struct 实例,然后您尝试在无法访问所述实例的 get struct 方法中访问该实例。 This will not work.这行不通。 Why are you trying to use getters and setters for this struct?你为什么要为这个结构使用 getter 和 setter? 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:如果您只想检查mystruct并且不想使用Dictionary<string, string>代替:

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:要做的最小更改是将实例 ( mystruct ) 传递给GetValue方法:

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.但我会回应其他评论和答案,除非您出于某种原因被迫使用结构,否则这不是一个伟大的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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