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

Phương thức Type.GetNestedTypes() trong C#

Phương thức Type.GetNestedTypes() trong C# được dùng để lấy các kiểu lồng nhau bên trong kiểu hiện tại.

Cú pháp

Hai nạp chồng:

public Type[] GetNestedTypes();
public abstract Type[] GetNestedTypes(BindingFlags bindingAttr);

Ví dụ 1 - 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("Nested Types...");
            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ả

Nested Types...
Subject+BasicSubject
Subject+AdvSubject

Ví dụ 2 - Lấy kiểu lồng nhau công khai

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("Nested Types...");
            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ả

Nested Types...
Subject+BasicSubject
Subject+AdvSubject