C# 进阶 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

遍历属性

  C#利用反射,可以获得一个类的所有属性名,以及该类的实例的所有属性的值。如下代码:

using System;
using System.Reflection;
namespace TestReflection
{
    class ReflectionExample
    {
        public static void Main()
        {
            test c = new test();
            Type t = c.GetType();
            foreach (PropertyInfo pi in t.GetProperties()) //t.GetProperties()获取所有属性的集合
            {
                Console.WriteLine(pi.Name); //显示属性的名字
            }
        }
    }
    class test  //定义类
    {
       public  int a { get; set; }
       public   int b { get; set; }
       public int cccc;
    }
}

注意:必须要设置了getset方法的属性,反射才能获得该属性。