C# 通过 类名 利用反射 获取类对象 以及为类中的成员变量赋值

 

定义Test类, 通过反射 获取Test对象 及为Test中的IntA 赋值

项目结构如下:

C# 通过 类名 利用反射 获取类对象 以及为类中的成员变量赋值

代码:

public class Test
    {
        public static int IntA { get; set; }

        public static string StringB { get; set; }
    } 


class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.Load("Common"); //程序集名称
            //从程序集中获取指定对象类型;
            Type type = assembly.GetType("Common.Test"); //程序集名称.类名
            Object obj = type.Assembly.CreateInstance(type.ToString());
            Console.WriteLine(type);
            Console.WriteLine(obj);
            //System.Reflection.PropertyInfo[]  propertyInfos= type.GetProperties();
            type.GetProperty("IntA").SetValue(obj,1) ;      
            Console.WriteLine(type.GetProperty("IntA").GetValue(obj));
            Console.ReadKey();
        }
    }

//获取静态类中的静态成员属性的值

typeof(类).GetProperty(字段名).GetValue(typeof(类)).ToString();