C# 可以利用反射给只读属性赋值吗?
2023-09-14 09:03:14 时间
ReflectTest rt = new ReflectTest();
rt.GetType().GetProperty("ID").SetValue(rt, "Guid", null);
MessageBox.Show(rt.ID);
public class ReflectTest
private string id;
[ReadOnly(true)]
public string ID
return id;
id = value;
运行winform程序输出:
java反射机制查找类的属性并赋值 先说一下需求:最近做一个项目其中需要将前台传来的数组存到数据库,但是这个表里有15个字段,集合是不固定的,然后要把这个集合的数值赋给这个类的相应属性,然后存到数据库中。集合长度应小于等于这个类属性的个数。
构造器、对象数组、对象属性、静态实例块、this关键字 它的名字:构造函数、构造方法、初始化方法。 构造条件? 以后我们如何去使用构造器? 你觉得那些对象中那些属性值是必要的,你就在构造器中提出来(就是你如果想创造对象必须要传入我所需要的参数) public class Dog {//这里就是一个简单的类、狗的类 String name;
C# 类相同属性赋值 原文:C# 类相同属性赋值 做项目时偶尔B类赋值给A类,碰巧A和B类型很多属性字段名是一样的,或者只是大小写不一样,这是可以利用泛型,反射来写一个自动化赋值的方法。 下面方法不考虑大小写不一样的情况,如果要考虑,可以使用字符串方法 ToUpper() 、ToLower() 后,对比字段名是否一样。
C#使用反射设置属性值 最近在Refix一个支持Excel文件导入导出功能时,发现有用到反射的相关技能。故而在网上查了些资料,通过代码调试加深下理解。 class Program static void Main(string[] args)
小注:
TypeDescriptor.GetProperties用来setvalue这没有作用:
TypeDescriptor.GetProperties(rt)["ID"].SetValue(rt, "Guid");
那么为什么TypeDescriptor.GetProperties用来setvalue没有效果呢?
将上面的代码拆成如下两句:
PropertyDescriptor prop = TypeDescriptor.GetProperties(rt)["ID"]; prop.SetValue(rt, "Guid");单点跟踪进去,可以发现:
在获取到PropertyDescriptor这个抽象类的实例后,在调用SetValue方法的时候,是从其子类ReflectPropertyDescriptor调用的。
而具体的实现是在子类:ReflectPropertyDescriptor中,从微软源码中找到ReflectPropertyDescriptor及SetValue
public override void SetValue(object component, object value) { #if DEBUG if (PropDescUsageSwitch.TraceVerbose) { string compName = "(null)"; string valName = "(null)"; if (component != null) compName = component.ToString(); if (value != null) valName = value.ToString(); Debug.WriteLine("[" + Name + "]: SetValue(" + compName + ", " + valName + ")"); #endif if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object invokee = GetInvocationTarget(componentClass, component); Debug.Assert(!IsReadOnly, "SetValue attempted on read-only property [" + Name + "]"); if (!IsReadOnly) { // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
if (changeService != null) { oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null); try { changeService.OnComponentChanging(component, this); catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; throw coEx; try { try { SecurityUtils.MethodInfoInvoke(SetMethodValue, invokee, new object[] { value }); OnValueChanged(invokee, EventArgs.Empty); catch (Exception t) { // Give ourselves a chance to unwind properly before rethrowing the exception. value = oldValue; // If there was a problem setting the controls property then we get: // ArgumentException (from properties set method) // == Becomes inner exception of TargetInvocationException // == caught here if (t is TargetInvocationException t.InnerException != null) { // Propagate the original exception up throw t.InnerException; else { throw t; finally { // Now notify the change service that the change was successful. if (changeService != null) { changeService.OnComponentChanged(component, this, oldValue, value); }
从代码中可以看出来,只读属性直接被跳过去了。。。。。。
那么PropertyInfo有没有什么限制呢?
PropertyInfo调用的SetValue如下所示:
在微软开源的代码中可以找到其具体实现如下:
[DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public override void SetValue(Object obj, Object value, Object[] index) SetValue(obj, value, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null); [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) MethodInfo m = GetSetMethod(true); if (m == null) throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd")); Object[] args = null; if (index != null) args = new Object[index.Length + 1]; for(int i=0;i index.Length;i++) args[i] = index[i]; args[index.Length] = value; else args = new Object[1]; args[0] = value; m.Invoke(obj, invokeAttr, binder, args, culture); }
暂时没有看到PropertyInfo调用的SetValue有什么限制
PropertyInfo.GetSetMethod 方法 (Boolean)
java反射机制查找类的属性并赋值 先说一下需求:最近做一个项目其中需要将前台传来的数组存到数据库,但是这个表里有15个字段,集合是不固定的,然后要把这个集合的数值赋给这个类的相应属性,然后存到数据库中。集合长度应小于等于这个类属性的个数。
构造器、对象数组、对象属性、静态实例块、this关键字 它的名字:构造函数、构造方法、初始化方法。 构造条件? 以后我们如何去使用构造器? 你觉得那些对象中那些属性值是必要的,你就在构造器中提出来(就是你如果想创造对象必须要传入我所需要的参数) public class Dog {//这里就是一个简单的类、狗的类 String name;
C# 类相同属性赋值 原文:C# 类相同属性赋值 做项目时偶尔B类赋值给A类,碰巧A和B类型很多属性字段名是一样的,或者只是大小写不一样,这是可以利用泛型,反射来写一个自动化赋值的方法。 下面方法不考虑大小写不一样的情况,如果要考虑,可以使用字符串方法 ToUpper() 、ToLower() 后,对比字段名是否一样。
C#使用反射设置属性值 最近在Refix一个支持Excel文件导入导出功能时,发现有用到反射的相关技能。故而在网上查了些资料,通过代码调试加深下理解。 class Program static void Main(string[] args)
相关文章
- c#数组赋初值_C#数组初始化
- C#控件splitContainer用法
- C#窗口句柄
- c# mysql executenonquery_C#与数据库访问技术之ExecuteNonQuery方法
- 【C#】C#获得计算机硬件信息和操作系统信息,ManagementObjectSearcher[通俗易懂]
- 浅析C# Dictionary实现原理
- dotnet C# 基于 INotifyPropertyChanged 实现一个 CLR 属性绑定辅助类
- C与MySQL结合一个简单的示例(c# mysql 例子)
- c#重写TabControl控件实现关闭按钮的方法
- C#读取XML中元素和属性值的实现代码
- C#Dynamic关键字之:调用属性、方法、字段的实现方法
- 解析C#中的装箱与拆箱的详解
- C#通过XML节点属性/属性值读取写入XML操作代码实例
- C#正则表达式分解和转换IP地址实例(C#正则表达式大全c#正则表达式语法)
- 支持多类型数据库的c#数据库模型示例
- C#Form自定义光标的简单实现
- C#类中的属性使用总结(详解类的属性)
- c#连接mysql数据库的方法
- C#中的集合用法分析
- C#实现去除Strings中空格的方法
- C#把数组中的某个元素取出来放到第一个位置的实现方法
- C#关于类的只读只写属性实例分析
- C#中Convert.ToString和ToString的区别分析
- C#用ComboBox控件实现省与市的联动效果的方法