【问题标题】:Converting FieldInfo value to a List When List type not known当列表类型未知时将 FieldInfo 值转换为列表
【发布时间】:2012-11-22 21:00:05
【问题描述】:

我有以下:

    [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;

函数中的参数名称为Struct和StructType。

我遍历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]。

然后,我的问题是,函数只知道StructType 的类型Struct,如果可能的话,我如何在 C# 中复制 VB 行为?

【问题讨论】:

  • 你想做什么?获取sections列表中的第一个对象,知道是List&lt;SectionStruct&gt;吗?
  • 问题是我在尝试获取第一个元素时不知道类型是SectionStruct。如果我知道它是什么,那就容易了。就像我说的,在 VB 中这非常容易,因为它会自动将其视为底层类型。 C# 没有,所以我需要弄清楚如何像底层类型一样处理它。
  • 但你确实知道。只是不是在编译时;)让我为你修复一些示例代码,同时教你一些naming conventions...
  • 谢谢@khillang,非常感谢。

标签: c# list reflection system.reflection


【解决方案1】:

这里有一些(非常简单的)示例代码,它们已经很清楚地说明了......我真的不想为你做所有事情,因为这可能是反思的一个很好的教训:)

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
        }
    }
}

【讨论】:

  • 百万谢谢@khillang。确实是宝贵的一课,而且如此简单。我觉得很昏暗,但很开心。
  • 太好了,你让它工作了!我猜想从 VB.NET 过渡到 C# 比你想象的更难;)
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2018-10-01
  • 1970-01-01
相关资源
最近更新 更多