简体   繁体   English

只知道名称就抛出异常?

[英]Throwing an exception knowing only the name?

If I have a C# List<string> of exception names (eg. InternalServerErrorException, ConflictException, etc), how would I go about instantiating and throwing the specific exception with nothing more than the string value?如果我有一个 C# List<string>异常名称(例如 InternalServerErrorException、ConflictException 等),我将如何实例化和抛出特定异常而仅使用字符串值?

To clarify, I have a simple name as a string pulled from another source, eg.澄清一下,我有一个简单的名称作为从另一个来源提取的字符串,例如。 "ConflictException". “冲突异常”。 I need to be able to throw that specific exception.我需要能够抛出那个特定的异常。

string myException = "ConflictException";

I cannot just do a throw new myException without first casting (or otherwise converting) to an actual Exception() type.我不能在没有首先转换(或以其他方式转换)为实际 Exception() 类型的情况下进行throw new myException I have tried to do a safe cast, but it cannot convert string to Exception.我试图做一个安全的演员,但它不能将字符串转换为异常。

Thanks for any ideas.感谢您的任何想法。

The short answer is: you can't.简短的回答是:你不能。

You can't because:你不能因为:

  • Exceptions in your list might not be loaded in your current app domain, which could make them impossible to load您的列表中的异常可能不会加载到您当前的应用程序域中,这可能会使它们无法加载
  • Exceptions don't have a consistent constructor signature, making it error prone to create them using reflection.异常没有一致的构造函数签名,使用反射创建它们很容易出错。 Although most exception types contain a ctor(string) , not all of them do.尽管大多数异常类型都包含ctor(string) ,但并非所有异常类型都包含。

You can try something like this, but keep in mind that it is error prone:您可以尝试这样的事情,但请记住,它很容易出错:

// Load all exceptions once and map their name to their type
var exceptions = (
    from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where type.IsSubclassOf(typeof(Exception))
    where !type.IsAbstract && !type.IsGenericTypeDefinition
    group type by type.Name into g
    select g)
    .ToDictionary(p => p.Key, p => p.First());

// Later on, load a type by its name
string myException = "ConflictException";

Type exceptionType = exceptions[myException];

// Create a new instance, assuming it has a ctor(string)
Exception exception = (Exception)Activator.CreateInstance(
    exceptionType, new object[] { "Some message" });

// throw the exception
throw exception;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM