gpt4 book ai didi

c# - 如何获取数组字段的 FieldInfo?

转载 作者:太空狗 更新时间:2023-10-30 00:36:40 27 4
gpt4 key购买 nike

我正在尝试从结构中获取数组值的字段信息。到目前为止,我有以下内容,但我不知道如何获取我想要的信息。

    [StructLayout(LayoutKind.Sequential)]
public struct Test
{
public byte Byte1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]
public Test2[] Test1;
}

BindingFlags struct_field_flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
FieldInfo[] all_struct_fields = typeof(Test).GetFields(struct_field_flags);
foreach (FieldInfo struct_field in all_struct_fields)
{
if(struct_field.FieldType.IsArray)
{
// Get FieldInfo for each value in the Test1 array within Test structure
}
}

如果我这样做了:

 Type array_type = struct_field.FieldType.GetElementType();

这将返回 Test2 类型,但我不想要数组的类型,我想要该结构的 FieldInfo 或字段,以便我可以在其中设置值。

最佳答案

很抱歉最初的错误答案。我懒得创建自己的 Test2 类型,所以我使用了一个字符串。这是正确答案(希望如此):

我用下面的代码做了你想做的:

class Program
{
static void Main(string[] args)
{
object sampleObject = GetSampleObject();
FieldInfo[] testStructFields = typeof(Test).GetFields();

foreach (FieldInfo testStructField in testStructFields)
{
if (testStructField.FieldType.IsArray)
{
// We can cast to ILIst because arrays implement it and we verfied that it is an array in the if statement
System.Collections.IList sampleObject_test1 = (System.Collections.IList)testStructField.GetValue(sampleObject);
// We can now get the first element of the array of Test2s:
object sampleObject_test1_Element0 = sampleObject_test1[0];

// I hope this the FieldInfo that you want to get:
FieldInfo myValueFieldInfo = sampleObject_test1_Element0.GetType().GetField("MyValue");

// Now it is possible to read and write values
object sampleObject_test1_Element0_MyValue = myValueFieldInfo.GetValue(sampleObject_test1_Element0);
Console.WriteLine(sampleObject_test1_Element0_MyValue); // prints 99
myValueFieldInfo.SetValue(sampleObject_test1_Element0, 55);
sampleObject_test1_Element0_MyValue = myValueFieldInfo.GetValue(sampleObject_test1_Element0);
Console.WriteLine(sampleObject_test1_Element0_MyValue); // prints 55
}
}
}

static object GetSampleObject()
{
Test sampleTest = new Test();
sampleTest.Test1 = new Test2[5];
sampleTest.Test1[0] = new Test2() { MyValue = 99 };
object sampleObject = sampleTest;
return sampleObject;
}
}

[StructLayout(LayoutKind.Sequential)]
public struct Test2
{
public int MyValue;
}

[StructLayout(LayoutKind.Sequential)]
public struct Test
{
public byte Byte1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public Test2[] Test1;
}

这是最重要的一行:

FieldInfo myValueFieldInfo = sampleObject_test1_Element0.GetType().GetField("MyValue");

它应该为您提供您正在谈论的 FieldInfo。

关于c# - 如何获取数组字段的 FieldInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1222802/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com