What's the difference between Func and Conv

2019-06-16 03:42发布

Looking at the signatures for the Func and Converter delegates,

public delegate TResult Func<T, TResult>(T arg);
public delegate TOutput Converter<TInput, TOutput>(TInput input);

I'm struggling to see the difference between the two. Surely, if we rename the generic type arguments, they essentially amount to the same thing?

Can anyone explain why they both exist, please?

标签: c# delegates
3条回答
我命由我不由天
2楼-- · 2019-06-16 03:58

Converter<,> was added in .NET 2.0. The various Funcs were added in 3.5 (I think). Now, sure, the framework designers could have said "Hey, we've already got a generic delegate for this", but it would have looked very odd to have all the other Funcs and not this one. And to avoid a breaking change Converter must be left in place.

查看更多
Juvenile、少年°
3楼-- · 2019-06-16 04:06

There is no difference. The reason for their existence is historical. Converter<T1,T2> was already available in .NET 2.0, but a whole range of Func<> delegate types were added later on. For consistency, Func<T,TResult> was added, but it did the same thing as Converter<T1,T2>.

查看更多
我只想做你的唯一
4楼-- · 2019-06-16 04:10

There are lots of delegate types that are effictively the same - for example:

  • ThreadStart
  • MethodInvoker
  • Action

all have the same void Foo() signature. Historically, the names were chosen by the specific use; but with LINQ and looking forwards, it seems clearer to focus on the signature - hence in .NET 3.5 they introduced things like Func<...> and Action<...> (families of delegates)

Unfortunately, they aren't really compatible at the variance level, so if you are using both you'll often have to shim between them. Which is a pain...

查看更多
登录 后发表回答