MST

星途 面试题库

面试题:C#反射机制中如何获取一个类的所有公共属性

请使用C#反射机制,编写代码获取一个给定类(假设为`SampleClass`)的所有公共属性,并输出属性名称。
20.5万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type type = typeof(SampleClass);
        PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine(property.Name);
        }
    }
}

class SampleClass
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}