C#专题——反射

    技术2026-03-02  9

    一、 GetType和typeof class Stack { public bool JudgeType() { Type type = typeof(T); return type == typeof(Int16) ? true : false;//获取Type类型的对象 } } class Stack2<T1, T2> {

    }

    二、成员调用 public class Employee { public int Id { get; set; } public string Name { get; set; } public string Title { get; set; } public int DeparementId { get; set; } public override string ToString() { return $"{Name }({Title })"; }

    }

    Employee employee1 = new Employee() { Title = “100” }; Type type1 = employee1.GetType();//对象引用调用GetType方法

    PropertyInfo[] propertyInfos = type1.GetProperties();//获取类型的所有属性 object value = propertyInfos[2].GetValue(employee1);//获取指定对象的属性的值

    三、泛型类型的反射 Stack stack1 = new Stack(); Console.WriteLine(stack1.JudgeType()); 四、判断类或者方法是否支持泛型 Stack stack1 = new Stack();

    Console.WriteLine(stack1.GetType().ContainsGenericParameters); Type type2 = typeof(System.Nullable<>); Type type3 = typeof(Stack<>); Console.WriteLine(type2.ContainsGenericParameters);//ContainsGenericParameters方法指示Type对象是否具有尚未被特定类型替代的类型参数 Console.WriteLine(type3.ContainsGenericParameters); Console.WriteLine(type3.IsGenericType);//IsGenericType指示该类型是否是泛型类型 Console.WriteLine(typeof(int).IsGenericType);

    五、获取泛型的类型参数

    Stack2<int, string> stack2 = new Stack2<int, string>(); Type type4 = stack2.GetType(); foreach (var item in type4.GenericTypeArguments )//获取类型的所有类型参数 { Console.WriteLine(item); }

    六、nameof操作符

    public class Person { public Person(string name, double height, int age) { this.Age = age; this.Name = name; this.Height = height; } public int Age { get; set; } public string Name { get; set; } private double _Height; public double Height { get { return _Height; } set { if(nameof (Height) =="Height")//nameof获取属性的名字 { _Height = value; Console.WriteLine("相等"); } } } }

    调用

    int num1 = 1000; string str1 = nameof(num1);//获取变量的名字 Console.WriteLine (str1); Person person1 =new Person("d",1,1);
    Processed: 0.025, SQL: 9