已经确定,当迭代List或Array时,编译器可以执行鸭子类型处理以消除一些开销(请参阅C#编译器中的鸭子类型),因为这些类型将其IEnumerator实现为堆栈分配的结构。
即使类型是通用的,但受约束实现IEnumerable时也是如此吗?
为了提供更多的特异性,选项B的运行开销是否可以低于A?
A:
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> collection)
{
foreach (var subCollection in collection)
foreach (var element in subCollection)
yield return element;
}
Run Code Online (Sandbox Code Playgroud)
B:
public static IEnumerable<T> Flatten<TList, T>(this TList collection)
where TList : IEnumerable<IEnumerable<T>>
{
foreach (var subCollection in collection)
foreach (var element in subCollection)
yield return element;
}
Run Code Online (Sandbox Code Playgroud) 在 BrowserStack 中进行测试后,我得出的结论是,自版本 81 以来,使用scrollTo()选项参数behavior: smooth在 Chrome 和 Edge 中不起作用。Edge 和 Chrome 的版本 80 都按预期工作。根据MDN 的说法,它应该可以在没有星号的情况下工作。(与 Safari 不同)
在诸如此之类的流行答案中,behavior: smooth推荐使用“使用”来在 Web 应用程序中启用平滑滚动。
这是一个小的可复制的:
<html>
<button onclick="goToAnchor('b')">Scroll to B</button>
<div id="a" style="height: 1000px; background-color: blue;">Blue</div>
<div id="b" style="height: 1000px; background-color: red;">Red</div>
<div id="c" style="height: 1000px; background-color: green;">Green</div>
</html>
<script>
function goToAnchor(anchor) {
let rect = document.getElementById(anchor).getBoundingClientRect();
window.scrollTo({
left: rect.left + window.pageXOffset,
top: rect.top + window.pageYOffset,
behavior: 'smooth',
});
}
</script>Run Code Online (Sandbox Code Playgroud)
预期的行为是浏览器窗口将视图平滑地插入红色 div。在我测试过的所有版本的 …
我不明白为什么GenericMethod<T>()无法推断出对的呼吁。我的实际问题包含更多通用参数,从而使调用代码非常冗长且难以阅读。
GenericMethod<T>() 如果参数本身是'T',则可以在没有显式类型参数的情况下调用它,但是约束不适用于委托,并且一旦您输入了受约束的类型参数,便回到第一个平方。
delegate void GenericDelegate<T>(T t);
static void GenericMethod<T>(GenericDelegate<T> _) { }
static void IntMethod(int _) { }
static void CallingMethod()
{
// The type arguments for method 'GenericMethod<T>(GenericDelegate<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
GenericMethod(IntMethod);
}
Run Code Online (Sandbox Code Playgroud)
是否有另一种方法可以使调用代码像此处所述一样简单?的GenericMethod<T>()是一个内部库的一部分。