首页 后端开发 C#.Net教程 C# 可以利用反射给只读属性赋值吗?

C# 可以利用反射给只读属性赋值吗?

Feb 17, 2017 am 10:54 AM

结论:可以

验证demo如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace IconTest

{

    public partial class Form2 : Form

    {

        public Form2()

        {

            InitializeComponent();

            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

        {

            get

            {

                return id;

            }

            set

            {

                id = value;

            }

        }

    }

}

登录后复制


运行winform程序输出:



小注:

TypeDescriptor.GetProperties用来setvalue这没有作用:

1

TypeDescriptor.GetProperties(rt)["ID"].SetValue(rt, "Guid");

登录后复制

那么为什么TypeDescriptor.GetProperties用来setvalue没有效果呢?

将上面的代码拆成如下两句:

1

2

PropertyDescriptor prop = TypeDescriptor.GetProperties(rt)["ID"];

prop.SetValue(rt, "Guid");

登录后复制

单点跟踪进去,可以发现:



在获取到PropertyDescriptor这个抽象类的实例后,在调用SetValue方法的时候,是从其子类ReflectPropertyDescriptor调用的。



而具体的实现是在子类:ReflectPropertyDescriptor中,从微软源码中找到ReflectPropertyDescriptor及SetValue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

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");

                    }

 

 

                    // Make sure that it is ok to send the onchange events

                    //

                    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如下所示:


在微软开源的代码中可以找到其具体实现如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

[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)



 以上就是C# 可以利用反射给只读属性赋值吗?的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
2 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

使用 C# 的活动目录 使用 C# 的活动目录 Sep 03, 2024 pm 03:33 PM

使用 C# 的 Active Directory 指南。在这里,我们讨论 Active Directory 在 C# 中的介绍和工作原理以及语法和示例。

C# 中的随机数生成器 C# 中的随机数生成器 Sep 03, 2024 pm 03:34 PM

C# 随机数生成器指南。在这里,我们讨论随机数生成器的工作原理、伪随机数和安全数的概念。

C# 中的访问修饰符 C# 中的访问修饰符 Sep 03, 2024 pm 03:24 PM

C# 中的访问修饰符指南。我们已经讨论了 C# 中访问修饰符的简介类型以及示例和输出。

C# 数据网格视图 C# 数据网格视图 Sep 03, 2024 pm 03:32 PM

C# 数据网格视图指南。在这里,我们讨论如何从 SQL 数据库或 Excel 文件加载和导出数据网格视图的示例。

C# 序列化 C# 序列化 Sep 03, 2024 pm 03:30 PM

C# 序列化指南。这里我们分别讨论C#序列化对象的介绍、步骤、工作原理和示例。

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 模式指南。在这里,我们讨论 C# 中模式的介绍和前 3 种类型,以及其示例和代码实现。

C# 中的质数 C# 中的质数 Sep 03, 2024 pm 03:35 PM

C# 素数指南。这里我们讨论c#中素数的介绍和示例以及代码实现。

C# 中的 Web 服务 C# 中的 Web 服务 Sep 03, 2024 pm 03:32 PM

C# Web 服务指南。在这里,我们讨论 C# 中的 Web 服务简介,包括技术使用、限制和示例。

See all articles