Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy các kiểu lồng nhau trong Type hiện tại C#

Ví dụ 1

Sử dụng GetNestedTypes() để lấy tất cả kiểu lồng nhau:

using System;

public class Demo {
    public static void Main() {
        Type type1 = typeof(Subject);
        try {
            Type[] type2 = type1.GetNestedTypes();
            Console.WriteLine("Các kiểu lồng nhau...");
            for (int i = 0; i < type2.Length; i++)
                Console.WriteLine("{0} ", type2[i]);
        }
        catch (ArgumentNullException e) {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

public class Subject {
    public class BasicSubject { }
    public class AdvSubject { }
}

Kết quả

Các kiểu lồng nhau...
Subject+BasicSubject
Subject+AdvSubject

Ví dụ 2

Sử dụng BindingFlags.Public để lọc:

using System;
using System.Reflection;

public class Demo {
    public static void Main() {
        Type type1 = typeof(Subject);
        try {
            Type[] type2 = type1.GetNestedTypes(BindingFlags.Public);
            Console.WriteLine("Các kiểu lồng nhau...");
            for (int i = 0; i < type2.Length; i++)
                Console.WriteLine("{0} ", type2[i]);
        }
        catch (ArgumentNullException e) {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

public class Subject {
    public class BasicSubject { }
    public class AdvSubject { }
}

Kết quả

Các kiểu lồng nhau...
Subject+BasicSubject
Subject+AdvSubject