[英]Get Variables in struct by name
我想使用结构中变量的名称从结构中的变量中获取值。 function 应该使用字符串来返回结构中具有此名称的变量的值。
在此示例中,“GetStingfromStruct”function 应返回“asdf”。 (当前代码只是一些测试并返回“System.String string1”)。
如果这个问题解决了,我还有一个问题。 有没有办法检查结构是否包含带有字符串名称的变量。 (为避免错误)
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;
}
您在 set struct 方法中声明了一个 struct 实例,然后您尝试在无法访问所述实例的 get struct 方法中访问该实例。 这行不通。 你为什么要为这个结构使用 getter 和 setter? 当您可以使用字典时,为什么要尝试使用结构?
可以按如下方式使用字典:
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
您可以使用反射:
在一般情况下,对于任意结构和任意字段,您可以放置
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();
然后您可以将其用作
string result = GetStringFromStruct(mystruct, "string1");
如果您只想检查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();
}
要做的最小更改是将实例 ( mystruct
) 传递给GetValue
方法:
private sting GetStingfromStruct(string variableName)
{
return (string)mystruct.GetType().GetField(variableName).GetValue(mystruct);
}
您还应该添加检查以确保字符串值实际上是字段名称等。
但我会回应其他评论和答案,除非您出于某种原因被迫使用结构,否则这不是一个伟大的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.