我知道关于foreach循环如何在C#中工作的基础知识(foreach循环如何在C#中工作)
我想知道是否使用foreach分配可能导致垃圾收集的内存?(适用于所有内置的系统类型).
例如,在System.Collections.Generic.List<T>类上使用Reflector ,这里是GetEnumerator的实现:
public Enumerator<T> GetEnumerator()
{
return new Enumerator<T>((List<T>) this);
}
Run Code Online (Sandbox Code Playgroud)
在每次使用时,这将分配一个新的枚举器(和更多的垃圾).
所有类型都这样做吗?如果是这样,为什么?(不能重用一个枚举器吗?)
我是C#的新手并对使用"var"有疑问
当我使用以下代码时,一切都很好
foreach(DataGridViewRow row in myGrid.Rows)
{
if (row.Cells[2].Value.ToString().Contains("51000"))
{
row.Cells[0].Value = "X";
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我改变DataGridViewRow为var我得到和错误的状态
'object'不包含'Cells'的定义,也没有扩展方法'Cells'可以找到接受'object'类型的第一个参数(你是否缺少using指令或汇编引用?)
我现在已经阅读了很多关于Duck Typing的内容,我似乎理解了这个概念.
我不明白的是,在什么情况下,放弃强大的典型编程的好处对于Duck Typing的好处是有效的.在什么情况下会使用Duck Typing而不是Interfaces和Inheritance?
我的意思是,如果你无论如何需要确保传递给Method的对象实现某些方法,为什么我不应该简单地定义一个接口?
为了清楚起见,我知道Duck Typing是如何工作的.我想知道何时使用它真的很有意义.
在哪种情况下你会使用
public bool MyMethod(dynamic obj)
Run Code Online (Sandbox Code Playgroud)
代替
public bool MyMethod(ISomeInterface obj)
//or
public bool MyMethod(SomeBaseClass obj)
Run Code Online (Sandbox Code Playgroud) 已经确定,当迭代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) public interface IInterface { }
public class MyClass { }
public static class Program {
public static void Main() {
IInterface myVariable = new MyClass();
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这个代码,因为工作MyClass确实满足IInterface,但我得到一个编译错误:
错误CS0266:无法将类型"MyClass"隐式转换为"IInterface".存在显式转换(您是否错过了演员?)
为什么?
我可以使用哪种解决方法不涉及显式转换?
我发现try-with-resources可用于任何实现该AutoCloseable接口的类。
public interface AutoCloseable {
void close() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
这是类在 Java 中支持try-with-resources的唯一标准吗(我的意思是,是否存在类不实现AutoCloseable接口但支持try-with-resources 的可能场景)?