繁体   English   中英

C#从方法签名实例化泛型类型

[英]C# instantiate generic type from method signature

我最近一直在研究泛型方法,遇到了如下所示的方法:

public static void Requires<TException>(bool condition, string message) where TException : Exception

据我了解,当使用上述方法时,您将提供一个从Exception继承的Type ,如果conditionfalse ,则会抛出所提供的Exception类型。

这是如何工作的?
TException实例,像这样throw new TException();
如果方法未知Type (它知道它继承了Exception类型),又如何传递message参数呢?

根据MSDN: System.Exception确实具有将字符串作为参数的构造函数。 此字符串表示消息。

借助Activator-Class,您可以执行以下非常简单的操作:

 using System;

public class Test
{

   public static void Requires<TException>(bool condition, string message) 
where TException : Exception
{
    Exception exception = (Exception)Activator.CreateInstance(typeof(TException),message);
    throw exception;
}

  public static void Main()
  {
      try
      {
          Requires<ArgumentNullException>(true,"Test");
      }
      catch(Exception e)
      {
          Console.WriteLine(e);
      }

   }
}

工作示例: http : //ideone.com/BeHYUO

据我了解,当使用上述方法时,您将提供一个从Exception继承的Type,如果条件为false,则会抛出所提供的Exception类型。

这取决于方法的实现,所要说明的是Requires方法的类型参数必须具有Exception的基本类型。 但是,如果条件为false ,则很有可能会创建该类型的异常。 一种方法是使用Activator.CreateInstance方法。

以及如果方法未知Type则如何传递message参数

Ned Stoyanov的答案类似,这取决于实现该方法的人员来决定如何使用此参数。 它可以用作嵌入例外的消息,也可以在其他地方使用,或者根本不使用。 参数名称仅表明其用途,但调用者无法保证将其按预期使用。 也可以称为djfhsfjfh

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM