且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否Enumerable.Cast< T>复制对象?

更新时间:2023-11-11 22:00:10

正如其名称所暗示的,演员LT; T&GT;()只是蒙上对象:

As its name implies, Cast<T>() just casts objects:

public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) { 
    IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
    if (typedSource != null) return typedSource; 
    if (source == null) throw Error.ArgumentNull("source");
    return CastIterator<TResult>(source);
}

static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
    foreach (object obj in source) yield return (TResult)obj; 
} 



在.NET中,它根本不可能复制任意对象。这将毫无意义演员LT; T&GT;()复制的东西。

请注意,如果 T 是值类型,演员LT; T&GT;()将会的复制结构;值类型的总是的复制。 (除非为 REF通过参数)

Note that if T is a value type, Cast<T>() will copy the structs; value types are always copied. (except when passed as ref parameters)