Skip to main content
 首页 » 编程设计

c#之异常与反射(reflection)

2024年02月24日24傻小

Web 服务有 SoapExtension,它包含错误处理程序和 xml 格式的序列化错误。

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

如何制作错误处理器,调用“Type”的错误?例如:

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

它必须调用 NullReferenceException。

请您参考如下方法:

您需要提供完全限定名称,即“System.NullReferenceException”。

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

编辑:这是一个简短但完整的有效程序:

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); 
    } 
}