Eho*_*ret 9 .net c# methods lambda
前几天,在我的一个实用程序中,ReSharper向我暗示了下面的代码段,声明定义委托的lambda ThreadStart可以转换为本地函数:
public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
if (!Enabled)
{
_threadCancellationRequested = false;
ThreadStart threadStart = () => NotificationTimer (ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);
Thread = new Thread(threadStart) {Priority = ThreadPriority.Lowest};
Thread.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
因此转变为:
public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
if (!Enabled)
{
_threadCancellationRequested = false;
void ThreadStart() => NotificationTimer(ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);
Thread = new Thread(ThreadStart) {Priority = ThreadPriority.Lowest};
Thread.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
后者相对于前者有什么好处,它只是关于性能吗?
我已经检查了下面的资源,但在我的例子中,好处并不那么明显:
您链接的第一个网站提到了本地功能的一些好处:
- lambda导致分配.
- 编写递归lambda没有优雅的方法.
- 他们不能使用yield return,可能还有其他一些东西.
一个有用的用例是迭代器:
错误的方法:
public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
//Since this method uses deferred execution,
//this exception will not be thrown until enumeration starts.
if (source == null)
throw new ArgumentNullException();
yield return something;
}
Run Code Online (Sandbox Code Playgroud)
正确的方法:
public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
if (source == null)
throw new ArgumentNullException();
return Iterator();
IEnumerable<T> Iterator() {
yield return something;
}
}
Run Code Online (Sandbox Code Playgroud)