简体   繁体   中英

C# instantiate generic type from method signature

I've been fooling around with generic methods lately and came across methods that look like this:

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

To my understanding, when using the above method you provide a Type that inherits from Exception and if the condition is false the provided Exception type is thrown.

How does this work under the hood?
Is the TException instantiated like so throw new TException(); ?
And how can you pass in the message parameter if the Type is unknown to the method (all it knows is that it inherits type Exception )?

According to MSDN : System.Exception does have constructor that takes a string as argument. This string represents the message.

With the help of the Activator-Class you can do the following pretty simple:

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

   }
}

Working example: http://ideone.com/BeHYUO

To my understanding, when using the above method you provide a Type that inherits from Exception and if the condition is false the provided Exception type is thrown.

That depends on the implementation of the method, all it is saying is that the type parameter of the Requires method must have a base type of Exception . But it is highly likely that it creates an exception of that type if the condition is false . One way to do that is with Activator.CreateInstance method.

And how can you pass in the message parameter if the Type is unknown to the method

Similarly to Ned Stoyanov 's answer, it's up to the person implementing the method to decide how this parameter will be used. It can be used as a message imbedded in the exception, it can be used somewhere else or it can be not used at all. The parameter name only suggests what it will be used for, but the caller has no guarantee that it will be used as he expects. It could be called djfhsfjfh as well .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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