例外与反思

dub*_*tor 1 c# reflection exception

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

<? Xml version = "1.0" encoding = "utf-8" standalone = "yes"?>
<Exception Type="System.NullReferenceException"> Exception text. </ Exception>
Run Code Online (Sandbox Code Playgroud)

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

Type _type = Type.GetType(doc.DocumentElement.Attributes["Type"].Value);
Run Code Online (Sandbox Code Playgroud)

它必须调用NullReferenceException.

Jon*_*eet 5

您需要提供完全限定的名称,即"System.NullReferenceException".

在这种特殊情况下,这就足够了 - 因为NullReferenceException在mscorlib中.但是,如果您需要其他异常 - 例如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);
    }
}
Run Code Online (Sandbox Code Playgroud)