是否强制转换 IList?到 T[] 类型的数组会导致枚举?
我有一个如下所示的方法:
T[] field;
public Method(IList<T> argument)
{
this.field = (T[])argument;
}
当执行方法主体时,在强制转换期间是否会进行枚举?如果基础类型不同,情况会改变吗?
I have a method that looks like:
T[] field;
public Method(IList<T> argument)
{
this.field = (T[])argument;
}
When the body of the method is executed does enumeration take place during the cast? Would that change if the underlying type was different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
argument
是对数组(类型为T
)的引用,那么就没有枚举——它只是一个简单的强制转换。如果
argument
是对List
或实现 IList 的另一个类的引用,则可能会出现转换异常。 (我说“可能”是因为可能存在到T[]
的隐式或显式转换 - 很可能不会)。编辑:正如 Jon 所指出的,通用方法中不会进行转换,因此上面的括号是不正确的。
If
argument
is a reference to an array (of typeT
), then there is no enumeration — it is a simple cast.If
argument
is a reference to aList<T>
or another class that implements IList then there will potentially be a casting exception. (I say potenially as there may be an implict or explict conversion toT[]
— most likely there won't be).Edit: as pointed out by Jon, a conversion won't be made in the generic method, so the above parenthesis is incorrect.
不,它不会枚举任何内容。如果
argument
实际上是T[]
,它将成功,或者如果不是,则抛出InvalidCastException
异常t。 (或者如果argument
为 null,则返回 null。)No, it won't enumerate anything. It will either succeed if
argument
actually is aT[]
, or throw anInvalidCastException
exception if it isn't. (Or return null ifargument
is null.)