【笔记】C# 通过反射获取属性

写程序时遇到的情况:需要本地化的数据作为类的静态属性,而数据的本地值是通过Key-Value的方式储存在资源里的,这时候就需要根据Key(字符串,储存属性名称)定位到对应的静态属性,于是就需要用到反射了。

反射首先需要获取这个对象的类型(Type),可以使用 typeof 或者 GetType方法,然后通过该类型(Type)的 GetProperty 方法获取某个属性的属性信息(PropertyInfo),这个方法接收一个字符串参数指明这个属性的名称,在上面的场景里,也就是传入Key,这样就能获取那个属性的信息了。到这里为止,所得到的都和类的实例无关。

之后通过属性信息(PropertyInfo)的 GetValue/SetValue 两个方法就能通过反射获取/修改某个类的实例的属性值,这两个方法都接收一个 Object 参数,指向要修改的类的实例(如果是 SetValue 则还需要接受另一个 Object 参数指定新的属性值)。如果要获取/修改的属性是类的静态属性,则无需传入实例(即传入 null 即可)。

以静态属性为例:

using System;
using System.Reflection;

namespace ReflectionExample
{
    class ExampleClass
    {
        public static string name { get; set; } = "test";
    }
    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(ExampleClass);
            string propertyName = "name";
            string value = "";
            if ((type != null) && (propertyName != null))
            {
                PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Static);
                if (property == null)
                {
                    throw new InvalidOperationException();
                }
                if (property.PropertyType != typeof(string))
                {
                    throw new InvalidOperationException();
                }
                value = (string)property.GetValue(null);
            }
            Console.WriteLine(value);
        }
    }
}

C#的反射支持字段、属性、方法和特性(Attribute),这里只是以属性为例,其他的可参考MSDN。