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

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

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

Cú pháp

Hai nạp chồng:

public Type GetNestedType(string name);
public abstract Type GetNestedType(string name, BindingFlags bindingAttr);

Ví dụ 1 - Lấy kiểu lồng nhau theo tên

using System;

public class Demo
{
    public static void Main()
    {
        Type type1 = typeof(Subject);
        try
        {
            Type type2 = type1.GetNestedType("AdvSubject");
            Console.Write("NestedType = " + type2);
        }
        catch (ArgumentNullException e)
        {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

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

Kết quả

NestedType = Subject+AdvSubject

Ví dụ 2 - Truyền null gây ngoại lệ

using System;

public class Demo
{
    public static void Main()
    {
        Type type1 = typeof(Subject);
        try
        {
            Type type2 = type1.GetNestedType(null);
            Console.Write("NestedType = " + type2);
        }
        catch (ArgumentNullException e)
        {
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

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

Kết quả

System.ArgumentNullException