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

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

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

发布评论

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

>www.elefans.com

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