C# delegate method signature - can you explain the syntax of this method signature? [duplicate]

StackOverflow https://stackoverflow.com/questions/23350525

  •  11-07-2023
  •  | 
  •  

Domanda

In the following method signature, after the method name CacheMe, what is the <inType, outType>? I cannot understand what this syntax means or stands for on the right side of the CacheMe method name. I understand what the <inType, outType> is on the left side of the CacheMe method name, but what is the <inType, outType> before the method parameter list?

public static Func<inType, outType> CacheMe<inType, outType>(Func<inType, outType> passedInFunctionToExecute)`

Thanks for any help understanding this syntax.

È stato utile?

Soluzione

Those are the type arguments. These are used to enforce type safety without sacrificing re usability. It's a little too big of a topic for a SO question but I recommend reading this; http://msdn.microsoft.com/en-us/library/512aeb7t.aspx or Jon Skeets C# In Depth which does a good job of explaining them.

As an example lets just talk about Dictionary<TKey, TValue> where TKey is the type of the key and TValue is the type of the value. You declare those arguments when you instantiate the collection. There are also ways to put some constraints on which types are allowed but I'll leave that to you to read about. Basically, if I declare;

 Dictionary<string, MyObjectType> dic = new Dictionary<string, MyObjectType>();

Then try someting like;

  dic.Add(1, InstanceOfMyObjectType);

I will get a compiler error because my collection will only take a string for the key and an instance of MyObjectType for the value.

Altri suggerimenti

Clearly, CacheMe is a generic method that takes two type parameters. In this case, the same type parameters being used for the Func generic delegate.

A Func is a generic delegate that returns a value, the last type in the type definition list is the return type, the others are the parameters (thus "inType" and "outType").

Another example of generic methods is the LINQ extension methods. For example, IEnumerable.Where looks like this:

IEnumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>);

It returns an IEnumerable of type "TSource", takes an IEnumerable of type "TSource" and a function that accepts a "TSource" and returns a boolean.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top