如何使用C#中的参数化构造函数创建一个泛型参数的实例 [英] How to create an instance of a generic type argument using a parameterized constructor in C#
问题描述
我正在尝试编写一个帮助器方法,它将记录一条消息,并使用相同的消息抛出指定类型的异常。我有以下内容:
I'm trying to write a helper method that would log a message and throw an exception of a specified type with the same message. I have the following:
private void LogAndThrow<TException>(string message, params object[] args) where TException : Exception, new()
{
message = string.Format(message, args);
Logger.Error(message);
throw new TException(message);
}
添加 new()
约束编译器抱怨没有它,我不能实例化 TException
。现在我得到的错误消息是创建类型参数TException的实例时不能提供参数。我尝试使用无参数构造函数创建实例,然后设置消息
属性,但它是只读的。
Before adding the new()
constraint the compiler complained that without it I can't instantiate TException
. Now the error message I get is "Cannot provide arguments when creating an instance of a type parameter 'TException'". I tried creating the instance with the parameterless constructor and then set the Message
property but it's read-only.
是这是语言的限制还是有一个我不知道的解决方案?也许我可以使用反射,但这对于这样一个简单的任务来说太过分了。 (和很丑,但这是一个个人意见的问题。)
Is this a limitation of the language or is there a solution I don't know about? Maybe I could use reflection but that's overkill for such a simple task. (And pretty ugly, but that's a matter of personal opinion.)
推荐答案
你可以使用 Activator.CreateInstance()
(这允许你传递参数)来创建一个 TException
的实例。然后,您可以抛出创建的 TException
。
You can use Activator.CreateInstance()
(which allows you to pass in arguments) to create an instance of TException
. Then, you could throw the created TException
.
例如:
private void LogAndThrow<TException>(string message, params object[] args) where TException : Exception, new()
{
message = string.Format(message, args);
Logger.Error(message);
TException exception = (TException)Activator.CreateInstance(typeof(TException), message);
throw exception;
}
这篇关于如何使用C#中的参数化构造函数创建一个泛型参数的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!