使用字符串变量来寻址结构字段
use a string variable to address a struct field
在 C# 中,我有一个包含许多字段的结构,例如一个叫做 "key"。我正在阅读一个 .ini 设置文件,其中包含所有结构字段的值。有没有办法在读取过程中将字段名称用作字符串(如下面的 myField 字符串数组)来寻址结构字段(见下文)?这将允许我基于字符串数组循环读取许多字段。
private struct Foo {
public string key;
...
}
private Foo FooInstance;
string inStr;
string[] myFields[] = new string[10]{ ("key", "nextKey", ... );
for (int i=0;i<myFields.Length;i++) {
GetPrivateProfileString(section,myFields[i],"",inStr,255,file);
[convert myField[i] to the relevant Foo.key field] = inStr;
}
结合 this SO answer and keep in mind that struct is a value type so you need to correctly handle 更新后传回的反射技术。
一个非常快速的解决方案可能如下所示:
struct Foo {
public string Key;
public string NextKey;
}
static class FooExtensions
{
public static void Set(this ref Foo obj, string key, string value) {
object boxed = obj; // need to box the value type so we can use it after SetValue
var f = typeof(Foo).GetField(key, BindingFlags.Public|BindingFlags.Instance);
f.SetValue(boxed, value);
obj = (Foo) boxed;
}
public static string Get(this Foo obj, string key)
{
var f = typeof(Foo).GetField(key, BindingFlags.Public|BindingFlags.Instance);
return (string)f.GetValue(obj);
}
}
void Main()
{
var f = default(Foo);
f.Set("Key", "test");
f.Set("NextKey", "test");
f.Get("Key").Dump();
}
在 C# 中,我有一个包含许多字段的结构,例如一个叫做 "key"。我正在阅读一个 .ini 设置文件,其中包含所有结构字段的值。有没有办法在读取过程中将字段名称用作字符串(如下面的 myField 字符串数组)来寻址结构字段(见下文)?这将允许我基于字符串数组循环读取许多字段。
private struct Foo {
public string key;
...
}
private Foo FooInstance;
string inStr;
string[] myFields[] = new string[10]{ ("key", "nextKey", ... );
for (int i=0;i<myFields.Length;i++) {
GetPrivateProfileString(section,myFields[i],"",inStr,255,file);
[convert myField[i] to the relevant Foo.key field] = inStr;
}
结合 this SO answer and keep in mind that struct is a value type so you need to correctly handle 更新后传回的反射技术。
一个非常快速的解决方案可能如下所示:
struct Foo {
public string Key;
public string NextKey;
}
static class FooExtensions
{
public static void Set(this ref Foo obj, string key, string value) {
object boxed = obj; // need to box the value type so we can use it after SetValue
var f = typeof(Foo).GetField(key, BindingFlags.Public|BindingFlags.Instance);
f.SetValue(boxed, value);
obj = (Foo) boxed;
}
public static string Get(this Foo obj, string key)
{
var f = typeof(Foo).GetField(key, BindingFlags.Public|BindingFlags.Instance);
return (string)f.GetValue(obj);
}
}
void Main()
{
var f = default(Foo);
f.Set("Key", "test");
f.Set("NextKey", "test");
f.Get("Key").Dump();
}