Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you only want a fixed delegate type with named parameters then you can just define your own delegate type:</p> <p>Func is just defined like this:</p> <pre><code>public delegate TResult Func&lt;in T, out TResult&gt;(T arg) </code></pre> <p>So you can define your own delegate type with the parametername you want.</p> <p>But in your example you want to preserve the delegate type passed in, so this doesn't work here. In theory you could define your function like this:</p> <pre><code>public static T Extend(T functionToWrap) { } </code></pre> <p>Unfortunately there are no good generic constraints which restrict the input type to a delegate with the right signature(Or even just delegates at all). But without these constraints the implementation would become so ugly, and you'd lose so much static type safety that IMO it's not worth it.</p> <p>One workaround is using:</p> <pre><code>new MyFunc(Extend(f)) </code></pre> <p>where MyFunc defines the parameternames you want.</p> <p>Or you could do the following:</p> <pre><code>public static T ConvertDelegate&lt;T&gt;(Delegate d) { if (!(typeof(T).IsSubclassOf(typeof(Delegate)))) throw new ArgumentException("T is no Delegate"); if (d == null) throw new ArgumentNullException(); MulticastDelegate md = d as MulticastDelegate; Delegate[] invList = null; int invCount = 1; if (md != null) invList = md.GetInvocationList(); if (invList != null) invCount = invList.Length; if (invCount == 1) { return (T)(object)Delegate.CreateDelegate(typeof(T), d.Target, d.Method); } else { for (int i = 0; i &lt; invList.Length; i++) { invList[i] = (Delegate)(object)ConvertDelegate&lt;T&gt;(invList[i]); } return (T)(object)MulticastDelegate.Combine(invList); } } public static TDelegate Extend&lt;TDelegate,TArg,TResult&gt;(Func&lt;TArg,TResult&gt; functionToWrap) where TDelegate:class { Func&lt;TArg,TResult&gt; wrappedFunc= DoTheWrapping(functionToWrap); return ConvertDelegate&lt;TDelegate&gt;(wrappedFunc); } </code></pre> <p>BTW the ConvertDelegate function can be used to get Co/Contravariance on Delegates even prior to .net 4.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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