MST

星途 面试题库

面试题:C#中反射如何获取类的属性信息

请简述在C#中使用反射获取一个类的所有公共属性名称和类型的步骤,并给出相关代码示例。
35.2万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
  1. 步骤
    • 使用Type类获取目标类的类型对象。可以通过typeof关键字或者GetType方法获取。
    • 使用Type类的GetProperties方法获取类的所有公共属性。该方法会返回一个PropertyInfo数组,每个PropertyInfo对象代表一个属性。
    • 遍历PropertyInfo数组,通过PropertyInfoName属性获取属性名称,通过PropertyInfoPropertyType属性获取属性类型。
  2. 代码示例
using System;
using System.Reflection;

class Program
{
    class MyClass
    {
        public int MyProperty1 { get; set; }
        public string MyProperty2 { get; set; }
    }

    static void Main()
    {
        // 获取MyClass的类型对象
        Type type = typeof(MyClass);

        // 获取所有公共属性
        PropertyInfo[] properties = type.GetProperties();

        // 遍历属性并输出名称和类型
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine($"属性名称: {property.Name}, 属性类型: {property.PropertyType}");
        }
    }
}