GetValue,GetConstantValue和GetRawConstantValue之间的区别

PropertyInfo类上的GetValueGetConstantValueGetRawConstantValue方法有什么区别? 遗憾的是,MSDN文档在这个问题上并不十分清楚。

GetConstantValueGetRawConstantValue都打算用于文字(在字段的情况下考虑const ,但在语义上它可以应用于不仅仅是字段) – 不同于GetValue ,它可以在运行时获得某些东西的实际值,一个常量值(通过GetConstantValue或者GetRawConstantValue )不依赖于运行时 – 它直接来自元数据。

那么我们得到了GetConstantValueGetRawConstantValue之间的区别。 基本上,后者是更直接和原始的forms。 这主要表现为enum成员; 例如 – 如果我有:

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

然后Foo.BGetConstantValueFoo.B ; 但是, GetRawConstantValue2 。 特别是,如果使用仅reflection上下文,则不能使用GetConstantValue ,因为这需要将值Foo ,这在使用仅reflection时无法执行。

我不知道你要做什么。 无论如何,如果您只想使用reflection检索属性的值,则必须使用GetValue。 就是这样的:

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

请注意,如果在此示例中调用GetConstantValue或GetRawConstantValue,则会得到InvalidOperationexception,因为该属性不是常量。

Marc完美地解释了GetConstantValue和GetRawConstantValue之间的区别。