如果我有一個 C#List<string>的例外名稱(例如 InternalServerErrorException、ConflictException 等),我將如何實體化和拋出特定例外而僅使用字串值?
澄清一下,我有一個簡單的名稱作為從另一個來源提取的字串,例如。“沖突例外”。我需要能夠拋出那個特定的例外。
string myException = "ConflictException";
我不能在throw new myException沒有首先轉換(或以其他方式轉換)為實際 Exception() 型別的情況下進行操作。我試圖做一個安全的演員,但它不能將字串轉換為例外。
感謝您的任何想法。
uj5u.com熱心網友回復:
簡短的回答是:你不能。
你不能因為:
- 您的串列中的例外可能不會加載到您當前的應用程式域中,這可能會使它們無法加載
- 例外沒有一致的建構式簽名,使用反射創建它們很容易出錯。盡管大多數例外型別都包含 a
ctor(string),但并非所有例外型別都包含。
您可以嘗試這樣的事情,但請記住,它很容易出錯:
// 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489152.html
上一篇:什么時候“嵌套堆疊展開”可以?
