【发布时间】:2010-05-17 09:28:51
【问题描述】:
我们在调用反射泛型委托时遇到了一些奇怪的事情。在某些情况下,使用附加的调试器我们可以进行不可能的调用,而没有调试器我们无法捕获任何异常和应用程序快速失败。
代码如下:
using System;
using System.Windows.Forms;
using System.Reflection;
namespace GenericDelegate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate Class2 Delegate1();
private void button1_Click(object sender, EventArgs e)
{
MethodInfo mi = typeof (Class1<>).GetMethod("GetClass", BindingFlags.NonPublic | BindingFlags.Static);
if (mi != null)
{
Delegate1 del = (Delegate1) Delegate.CreateDelegate(typeof (Delegate1), mi);
MessageBox.Show("1");
try
{
del();
}
catch (Exception)
{
MessageBox.Show("No, I can`t catch it");
}
MessageBox.Show("2");
mi.Invoke(null, new object[] {});//It's Ok, we'll get exception here
MessageBox.Show("3");
}
}
class Class2
{
}
class Class1<T> : Class2
{
internal static Class2 GetClass()
{
Type type = typeof(T);
MessageBox.Show("Type name " + type.FullName +" Type: " + type + " Assembly " + type.Assembly);
return new Class1<T>();
}
}
}
}
有两个问题:
- 调试器和不带调试器的行为不同
- 如果没有调试器,您无法通过 clr 技巧捕获此错误。这不是 clr 例外。有内存访问,读取内部代码内部的零指针。
用例: 您为您的应用程序开发类似插件系统的东西。您阅读外部程序集,找到某种类型的合适方法,然后执行它。我们只是忘记了我们需要检查的类型是泛型还是非泛型。在 VS(和 .net 从 2.0 到 4.0)下一切正常。被调用函数不使用泛型类型和类型参数的静态上下文。但是没有 VS 应用程序失败,没有声音。我们甚至无法识别调用堆栈附加调试器。
使用 .net 4.0 测试
问题是为什么 VS 捕获但运行时没有?
【问题讨论】:
标签: c# .net reflection delegates generics