Difference between GetValue, GetConstantValue and

2019-04-19 04:42发布

What is the difference between the GetValue, GetConstantValue and GetRawConstantValue methods on the PropertyInfo class? The MSDN documentation unfortunately isn't very clear on the subject.

标签: c# reflection
2条回答
别忘想泡老子
2楼-- · 2019-04-19 05:11

I don't know what you are trying to do. Anyway, if you simply want to retrieve the value of a property using reflection you have to use GetValue. I.e. something like this:

     private string _foo = "fooValue";

     public string Foo
     {
         get { return _foo; }
         set { _foo = value; }
     }

     public void Test()
     {
         PropertyInfo pi = this.GetType().GetProperty("Foo");
         string v = (string)pi.GetValue(this, null);
     }

Note that if you call GetConstantValue or GetRawConstantValue in this example you get an InvalidOperationexception, since the property is not constant.

The difference between GetConstantValue and GetRawConstantValue has been explained perfectly by Marc.

查看更多
欢心
3楼-- · 2019-04-19 05:12

Both GetConstantValue and GetRawConstantValue are intended for use with literals (think const in the case of fields, but semantically it can apply to more than just fields) - unlike GetValue which would get the actual value of something at runtime, a constant value (via GetConstantValue or GetRawConstantValue) is not runtime dependent - it is direct from metadata.

So then we get to the difference between GetConstantValue and GetRawConstantValue. Basically, the latter is the more direct and primitive form. This shows mainly for enum members; for example - if I had an:

enum Foo { A = 1, B = 2 }
...
const Foo SomeValue = Foo.B;

then the GetConstantValue of SomeValue is Foo.B; however, the GetRawConstantValue of SomeValue is 2. In particular, you can't use GetConstantValue if you are using a reflection-only context, as that would require boxing the value to a Foo, which you can't do when using reflection-only.

查看更多
登录 后发表回答