gpt4 book ai didi

c# - 当列表类型未知时将 FieldInfo 值转换为列表

转载 作者:行者123 更新时间:2023-11-30 22:23:08 25 4
gpt4 key购买 nike

我有以下内容:

    [Serializable()]
public struct ModuleStruct {
public string moduleId;
public bool isActive;
public bool hasFrenchVersion;
public string titleEn;
public string titleFr;
public string descriptionEn;
public string descriptionFr;
public bool isLoaded;
public List<SectionStruct> sections;
public List<QuestionStruct> questions;
}

我创建了一个实例并填充它(内容与问题无关)。我有一个将实例化对象作为一个参数的函数,我们称它为模块,并将此对象的类型作为另一个参数:module.GetType()

然后这个函数将使用反射,并且:

    FieldInfo[] fields = StructType.GetFields();
string fieldName = string.Empty;

函数中的参数名称是StructStructType

我循环遍历 Struct 中的字段名称,提取不同字段的值并对其进行处理。一切都很好,直到我到达:

    public List<SectionStruct> sections;
public List<QuestionStruct> questions;

该函数仅通过StructType 知道Struct 的类型。在 VB 中,代码很简单:

    Dim fieldValue = Nothing
fieldValue = fields(8).GetValue(Struct)

然后:

    fieldValue(0)

获取列表部分中的第一个元素;但是,在 C# 中,相同的代码不起作用,因为 fieldValue 是一个对象,我不能对对象执行 fieldValue[0]

那么我的问题是,假设函数只知道 StructTypeStruct 类型,我如何在 C# 中复制 VB 行为,如果它是偶数可能吗?

最佳答案

这里有一些(非常简单的)示例代码,非常详细......我真的不想为你做所有事情,因为这可能是一个很好的反射(reflection)类(class):)

private void DoSomethingWithFields<T>(T obj)
{
// Go through all fields of the type.
foreach (var field in typeof(T).GetFields())
{
var fieldValue = field.GetValue(obj);

// You would probably need to do a null check
// somewhere to avoid a NullReferenceException.

// Check if this is a list/array
if (typeof(IList).IsAssignableFrom(field.FieldType))
{
// By now, we know that this is assignable from IList, so we can safely cast it.
foreach (var item in fieldValue as IList)
{
// Do you want to know the item type?
var itemType = item.GetType();

// Do what you want with the items.
}
}
else
{
// This is not a list, do something with value
}
}
}

关于c# - 当列表类型未知时将 FieldInfo 值转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519910/

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