[英]How can I implicitly convert List<Foo> to List<Bar> given that there's a cast operator defined?
I have a type Bar
that defines an implicit cast operator: 我有一个Bar
类型,它定义了一个隐式强制转换运算符:
public static implicit operator Bar(Foo foo)
{
return new Bar(foo.property);
}
Converting single objects works great, but now I have a List<Foo>
and I need a List<Bar>
. 转换单个对象的效果很好,但是现在我有了一个List<Foo>
并且我需要一个List<Bar>
。
I found this workaround: 我发现此解决方法:
List<Bar> barList = fooList.ConvertAll<Bar>(item => item);
which seems to do the trick, but it's somewhat defeating the point of an implicit cast operator if I have to apply it in this somewhat explicit sense. 这似乎可以解决问题,但是如果我必须在某种显式意义上应用它,那么它在某种程度上克服了隐式强制转换运算符的观点。 Is there any way to make the implicit conversion work for lists? 有什么方法可以使隐式转换适用于列表?
Unfortunately, you cannot make this cast implicit, although the reason is somewhat unexpected: when you explicitly provide a type argument to a generic method, C# requires you to provide all remaining arguments as well. 不幸的是,尽管原因有些出乎意料,但是您不能使此强制转换隐式:当您为通用方法显式提供类型实参时,C#还要求您提供所有剩余的实参。 It is this all-or-nothing approach that lets you write this 正是这种全有或全无的方法可以让您编写此内容
List<Bar> barList = fooList.Select(item => (Bar)item).ToList();
or this 或这个
List<Bar> barList = fooList.Select<Foo,Bar>(item => item);
but it does not let you write this: 但是它不允许您这样写:
List<Bar> barList = fooList.Select<...,Bar>(item => item);
// ^^^
// |
// Figure this out from the context |
Theoretically, C# could capture Foo
from the type of item
, but it does not have a feature to do it. 从理论上讲,C# 可以从item
的类型中捕获Foo
,但是它没有执行此操作的功能。
LINQ's Cast<T>
is not going to work either, because it treats items being cast as plain object
s, thus ignoring any conversion operators that may be defined on them. LINQ的Cast<T>
也不起作用,因为它会将要转换的项目视为普通object
,从而忽略了可能在其上定义的任何转换运算符。
Since you are required to specify both the "from" and the "to" types, a solution based on generics is not going to be any better than your solution based on ConvertAll
. 由于需要同时指定“ from”和“ to”类型,因此基于泛型的解决方案不会比基于ConvertAll
的解决方案更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.