2

私は次のものを持っています:

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

これのインスタンスを作成してデータを入力します(質問に関係のないコンテンツ)。インスタンス化されたオブジェクトを1つのパラメーターとして受け取り、それをモジュールと呼び、このオブジェクトのタイプをもう1つのパラメーターとして受け取る関数がありますmodule.GetType()

この関数は、リフレクションを使用して、次のようになります。

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

Struct関数のパラメーター名はとStructTypeです。

内のフィールド名をループしStruct、さまざまなフィールドの値と値を取得して、それを使用して何かを実行します。私が到達するまで、すべてが順調です:

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

Structこの関数は、 byのタイプのみを認識しStructTypeます。VBでは、コードは次のとおりです。

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

その後:

    fieldValue(0)

リストセクションの最初の要素を取得します。ただし、C#では、fieldValueがオブジェクトであり、オブジェクトに対して実行できないため、同じコードは機能しませんfieldValue[0]

Structそれで、私の質問は、関数がbyのタイプしか知らStructTypeないということですが、可能であれば、C#でVBの動作を複製するにはどうすればよいですか?

4

1 に答える 1

3

ここにいくつかの(非常に単純な)サンプルコードがありますが、これはかなり詳しく説明されています...これは振り返りの素晴らしいレッスンになる可能性があるため、私は本当にあなたのためにすべてをやりたくありません:)

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
        }
    }
}
于 2012-11-22T23:10:38.507 に答える