例外与反思 [英] Exception and Reflection

查看:80
本文介绍了例外与反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Web服务具有SoapExtension,其中包含错误处理程序和以xml格式序列化错误。

The web service has SoapExtension, which contains an error handler and serializing error in a format xml.

<? Xml version = "1.0" encoding = "utf-8" standalone = "yes"?>
<Exception Type="System.NullReferenceException"> Exception text. </ Exception>

如何制作错误处理程序,哪个类型调用错误?例如:

How to make error handler, which call error of "Type"? E.g.:

Type _type = Type.GetType(doc.DocumentElement.Attributes["Type"].Value);

必须调用NullReferenceException。

It must to call NullReferenceException.

推荐答案

您需要提供标准名称,即 System.NullReferenceException。

You need to provide the fully-qualified name, i.e. "System.NullReferenceException".

在这种情况下,这就足够了-因为 NullReferenceException 在mscorlib中。但是,如果您需要其他例外,例如 ConstraintException (位于System.Data程序集中)-您还需要提供完整的程序集名称。 Type.GetType(string)仅在当前执行的程序集和mscorlib中查找未指定程序集的类型名称。

In this particular case, that's enough - because NullReferenceException is in mscorlib. However, if you need other exceptions - such as ConstraintException, which lives in the System.Data assembly - you'd need to provide the full assembly name too. Type.GetType(string) only looks in the currently executing assembly and mscorlib for type names which don't specify the assembly.

编辑:这是一个简短但完整的程序,可以正常工作:

Here's a short but complete program which works:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        string typeName = "System.NullReferenceException";
        string message = "This is a message";
        Type type = Type.GetType(typeName);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
        object exception = ctor.Invoke(new object[] { message });
        Console.WriteLine(exception);
    }
}

这篇关于例外与反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆