[英]Finding index of an element in a List<FieldInfo> where FieldInfo represents a List<T>
[英]Converting FieldInfo value to a List When List type not known
我有以下幾點:
[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
的StructType
。 在VB中,代碼很簡單:
Dim fieldValue = Nothing
fieldValue = fields(8).GetValue(Struct)
進而:
fieldValue(0)
獲取列表部分中的第一個元素; 但是,在 C# 中,相同的代碼不起作用,因為fieldValue
是一個對象,我不能在對象上執行fieldValue[0]
。
那么,我的問題是,該函數僅通過StructType
知道Struct
的類型,如果可能的話,如何在 C# 中復制 VB 行為?
這里有一些(非常簡單的)示例代碼,這些代碼非常詳細......我真的不想為你做所有的事情,因為這可能是反思的一個很好的教訓:)
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.