博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#利用反射创建对象并进行赋值

Posted on 2024-07-02 21:26  火冰·瓶  阅读(2)  评论(0编辑  收藏  举报
Type classType = typeof(ClassName);     // 获取类的type

string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
Type classType = Type.GetType(path);//加载类型
Type classType = Type.GetType("类的完全限定名");   // 也可以根据类的完全限定名得到type

object myObj = Activator.CreateInstance(ClassType); //创建对象

PropertyInfo propertyInfo = classType.GetProperty("属性名称"); //获取到属性 Type pt = propertyInfo.PropertyType; //获取到属性的type
propertyInfo.SetValue(myObj, xxx); //xxx是需要进行赋值的值,类型必须跟此属性一致,否则会报错 propertyInfo.SetValue(myObj, Convert.ChangeType(xxx, pt)); //xxx是需要进行赋值的值,增加了类型转换,如果属性是Nullable,转换时会报错 propertyInfo.SetValue(myObj, propertyInfo.PropertyType.Name.Contains("Nullable") ? Convert.ChangeType(xxx, Nullable.GetUnderlyingType(pt)) : Convert.ChangeType(xxx, pt)); ///xxx是需要进行赋值的值,增加了类型转换和Nullable判断,终极用法