Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the following code to create a delegate, which is late bound in the type parameter. See also <a href="http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx" rel="nofollow">How to: Examine and Instantiate Generic Types with Reflection</a>.</p> <pre><code>abstract class ActionHelper { protected abstract Delegate CreateActionImpl(); // A subclass with a static type parameter private class ActionHelper&lt;T&gt; : ActionHelper { protected override Delegate CreateActionImpl() { // create an Action&lt;T&gt; and downcast return new Action&lt;T&gt;(obj =&gt; Console.WriteLine("Called = " + (object)obj)); } } public static Delegate CreateAction(Type type) { // create the type-specific type of the helper var helperType = typeof(ActionHelper&lt;&gt;).MakeGenericType(type); // create an instance of the helper // and upcast to base class var helper = (ActionHelper)Activator.CreateInstance(helperType); // call base method return helper.CreateActionImpl(); } } // Usage // Note: The "var" is always "Delegate" var @delegate = ActionHelper.CreateAction(anyTypeAtRuntime); </code></pre> <p>That said, I don't recommend using this method. Instead, use </p> <pre><code>Action&lt;object&gt; action = obj =&gt; Console.WriteLine("Called = " + obj); </code></pre> <p>It offers</p> <ul> <li><p>The same functionality.</p> <p>Your original code <code>"Called = " + obj"</code> calls <code>.ToString()</code> on the parameter. So does the above.</p></li> <li><p>No performance difference.</p> <p>If the <code>obj</code> parameter is a value type, both variants perform a boxing operation. The boxing in the first is not obvious, but <code>"Called = " + obj"</code> boxes value types.</p></li> <li><p>Shorter and less error-prone.</p></li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload