如何在C#中使用参数的构造函数来创建一个泛型类型参数的实例

编程入门 行业动态 更新时间:2024-10-26 00:26:47
本文介绍了如何在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#中使用参数的构造函数来创建一个泛型类型参数的实例

本文发布于:2023-11-02 15:08:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552723.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   创建一个   函数   实例   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!