我有一个 扩展程序
:
public static T GetPrivatePropertyValue<T>(this object obj, string propName)
{
if (obj == null) throw new ArgumentNullException("obj");
PropertyInfo pi = obj.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (pi == null) throw new ArgumentOutOfRangeException("propName", String.Format("Property {0} was not found in Type {1}", propName, obj.GetType().FullName));
return (T)pi.GetValue(obj, null);
}
我正在尝试将其用作:
menuItem.GetPrivatePropertyValue<RadMenuItem>("ParentItem");
但是我在这里遇到了错误:
return (T)pi.GetValue(obj, null);
which is:
(T)pi.GetValue(obj, null) 'pi.GetValue(obj, null)' threw an exception of type 'System.MethodAccessException' Telerik.Windows.Controls.RadMenuItem
menuItem
是Telerik.Windows.Controls.RadMenuItem
类的实例。
我想要的字段是
internal RadMenuItem ParentItem
{
get
{
return ItemsControl.ItemsControlFromItemContainer(this) as RadMenuItem;
}
}
我的代码有什么问题?是因为这个属性是内部的吗?
EDIT
这是我的堆栈跟踪:
{System.MethodAccessException: Attempt by method 'MyApp.Extensions.GetPrivatePropertyValue<System.__Canon>(System.Object, System.String)' to access method 'Telerik.Windows.Controls.RadMenuItem.get_ParentItem()' failed.
at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at MyApp.Extensions.GetPrivatePropertyValue[T](Object obj, String propName)
at MyApp.Calendar.OnContextMenuItemClick(Object sender, RadRoutedEventArgs e)}
也许这很重要:我的应用程序技术是Silverlight 4