gpt4 book ai didi

c# - 反射方法AccessException

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:18 29 4
gpt4 key购买 nike

我在 Silverlight 中有一个简单的代码:

public void temp()
{
try
{
WriteableBitmap obj = new WriteableBitmap(10, 10);

//PropertyInfo pr = obb.GetType().GetProperty("Pixels");
Type type = obj.GetType();
Type typeofType = type.GetType();

MethodInfo getPropMethod = typeofType.GetMethod("GetProperty", new Type[] { typeof(string) }); //get method info
PropertyInfo pix1 = type.GetProperty("Pixels"); // first call - no exceptions
PropertyInfo pix2 = (PropertyInfo)getPropMethod.Invoke(type, new object[] { "Pixels" }); // second call - MethodAccessException
}
catch (Exception ex)
{
}
}

方法 GetProperty 的第一次调用执行成功并且没有抛出异常。但是第二次调用 - methodInfo.Invoke 抛出 MethodAccessException - 为什么会发生这种情况?

异常和堆栈跟踪:

MethodAccessException: Attempt by security transparent method 'System.Type.GetProperty(System.String)' to access security critical method 'SilverlightApplication3.MainPage.temp()' failed.

in System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
in System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
in System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
in SilverlightApplication3.MainPage.temp()

最佳答案

Silverlight 中的反射仅限于编译时可用的内容,也许您第一次调用函数时条件已满足,但在第一次调用后某些内容发生变化并且反射无法执行。

In Silverlight, you cannot use reflection to access private types and members. If the access level of a type or member would prevent you from accessing it in statically compiled code, you cannot access it dynamically by using reflection.

引用here用于文档

关于c# - 反射方法AccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27546260/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com