【问题标题】:How can I implicitly convert List<Foo> to List<Bar> given that there's a cast operator defined?鉴于定义了强制转换运算符,如何将 List<Foo> 隐式转换为 List<Bar>?
【发布时间】:2016-05-19 18:49:24
【问题描述】:

我有一个类型 Bar,它定义了一个隐式转换运算符:

public static implicit operator Bar(Foo foo)
{
    return new Bar(foo.property);
}

转换单个对象效果很好,但现在我有一个List&lt;Foo&gt;,我需要一个List&lt;Bar&gt;

我找到了这个解决方法:

List<Bar> barList = fooList.ConvertAll<Bar>(item => item);

似乎可以解决问题,但如果我必须在这种有点明确的意义上应用它,它就有点违背了隐式转换运算符的意义。有什么方法可以使隐式转换对列表起作用?

【问题讨论】:

标签: c# list type-conversion


【解决方案1】:

不幸的是,您不能使这种强制转换为隐式,尽管原因有些出乎意料:当您显式为泛型方法提供类型参数时,C# 要求您也提供所有剩余的参数。正是这种全有或全无的方法让您编写此代码

List<Bar> barList = fooList.Select(item => (Bar)item).ToList();

或者这个

List<Bar> barList = fooList.Select<Foo,Bar>(item => item);

但它不允许你这样写:

List<Bar> barList = fooList.Select<...,Bar>(item => item);
//                                 ^^^
//                                  |
// Figure this out from the context |

理论上,C#可以item的类型中捕获Foo,但它没有这样做的功能。

LINQ 的 Cast&lt;T&gt; 也不起作用,因为它将被强制转换的项目视为普通的 objects,因此忽略了可能在它们上定义的任何转换运算符。

由于您需要同时指定“from”和“to”类型,基于泛型的解决方案不会比基于ConvertAll 的解决方案更好。

【讨论】:

  • fooList.OfType&lt;Bar&gt;().ToList() 在这里不起作用吗?或者它是否遇到关于演员如何发生的同样问题?
  • @RobV OfType&lt;Bar&gt; 将返回一个空的IEnumerable&lt;Bar&gt;:它应用与Cast&lt;Bar&gt; 相同的逻辑,但在无法进行强制转换时跳过元素而不是抛出异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
相关资源
最近更新 更多