如何在C#中使用参数的构造函数来创建一个泛型类型参数的实例 [英] How to create an instance of a generic type argument using a parameterized constructor in C#

查看:872
本文介绍了如何在C#中使用参数的构造函数来创建一个泛型类型参数的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写这将记录一个消息,并抛出一个指定的类型与同一消息的异常的helper方法。我有以下几点:

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

在添加新()约束编译器抱怨说,没有它,我无法实例 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆