【问题标题】:Access Value of TextSegment by reflection通过反射访问TextSegment的值
【发布时间】:2013-03-30 18:00:19
【问题描述】:

我在 Object 类型的对象中有一个“System.Windows.Documents.TextSegment”类型的对象。我不能在我的代码中使用 TextSegment-Struct,因为它是 .net 框架的内部代码。

我想要做的是访问 TextSegment 类型对象中的 Start- 和 End-Property。我通过反射尝试了以下代码:

// This object is of type TextSegment
object textSegment = segments[0];
FieldInfo info = textSegment.GetType().GetField("_start", BindingFlags.IgnoreCase | 
   BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance| BindingFlags.Static;

现在我不知道如何访问 FieldInfo 的值。

我用以下代码试了一下:

object value1 = info.GetValue(segments[0]);
object value2 = info.GetValue(null);

但没有任何效果。

如何获取 TextSegment 的值?

【问题讨论】:

  • 你可以试试下面的var value1 = segments.GetType().GetProperties().FirstOrDefault( p => p.Name == yourPropertyName);
  • 不,这不起作用。我为 value1 得到 null
  • 我刚刚意识到你想要 FieldInfo 看看这个 Stackoverflow 帖子我在想 PropertyInfo stackoverflow.com/questions/5090224/…

标签: c# wpf reflection


【解决方案1】:

那个代码响了a bell ;)...

您有一个错字(BindingFlags 末尾缺少括号),并且在 BindingFlags 中,您只需要 Instance 和 NonPublic,但我找不到真正的问题。

也许你需要提供更多代码,因为我已经检查过了,这对我来说很好:

您是否检查过该值实际上不为空?

【讨论】:

  • 我看到的和你一模一样。但是我如何存储这个?我无法创建 TextPointer 或其他对象的对象。如何将 Start 和 End 的值放入属性中。这就是问题所在...... :(
  • 我不太明白。如果 value1 像这样出现在调试器中,你已经有了它,不是吗?将其存储在 object 类型的属性中。也许你需要告诉我你想用它做什么。
  • 是的,我当然可以将 Start-Property 存储到对象类型的属性中。但我需要访问 Start 的具体值。这就是问题。如果我将它存储到一个对象中,我将无法访问属性。
  • DocumentSequenceTextPointer 是一个内部密封类,您将无法存储在允许您轻松访问其属性的类型中。如果您需要这些属性,则必须再次使用反射:value1.GetType().GetProperty/GetField...
猜你喜欢
  • 2022-01-11
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多