返回 `Enumerable.Empty()` 是什么意思?

huangapple go评论61阅读模式
英文:

OneOf return Enumerable.Empty<Item>()?

问题

如何使用C#的OneOf包返回Enumerable.Empty<ExchangeRate>()?

public async Task&lt;OneOf&lt;IEnumerable&lt;ExchangeRate&gt;, Error&gt;&gt; GetResults()
{
     return OneOf&lt;IEnumerable&lt;ExchangeRate&gt;, Error&gt;.FromT0(Enumerable.Empty&lt;ExchangeRate&gt;());
}

错误:无法隐式转换类型'System.Collections.Generic.IEnumerable&lt;Proj.ExchangeRate&gt;'为'OneOf.OneOf&lt;System.Collections.Generic.IEnumerable&lt;Proj.ExchangeRate&gt;, Proj.Error&gt;'

是否有更好的方法?例如,创建一个具有默认值为Enumerable.Empty&lt;Item&gt;()NoResults对象的Value属性,然后将其包括在OneOf返回类型的列表中?

英文:

How to return Enumerable.Empty<ExchangeRate>() using the OneOf package for C#?

public async Task&lt;OneOf&lt;IEnumerable&lt;Item&gt;, Error&gt;&gt; GetResults()
{
     return Enumerable.Empty&lt;Item&gt;(); // error
}

Error: Cannot implicitly convert type &#39;System.Collections.Generic.IEnumerable&lt;Proj.Item&gt;&#39; to &#39;OneOf.OneOf&lt;System.Collections.Generic.IEnumerable&lt;Proj.Item&gt;, Proj.Error&gt;&#39;

Is there a better approach? i.e. creating a new NoResults object with a Value property with a default value of Enumerable.Empty&lt;Item&gt;(), and then include it in the list of OneOf return types?

答案1

得分: 2

首选方式是使用OneOf定义的隐式转换运算符,所以你只需要返回一个值(就像你尝试过的那样),隐式转换运算符会自动处理。但是由于你将OneOf的类型之一定义为接口,用户定义的转换将不起作用。

要使其起作用,你可以使用在OneOf&lt;T0,T1&gt;类型上定义的静态方法:

return OneOf&lt;IEnumerable&lt;Item&gt;, Error&gt;.FromT0(Enumerable.Empty&lt;Item&gt;());

英文:

The preferred way is to use the implicit operator that the OneOf has defined, so you would just return a value (as you've tried) and the implicit conversion operator would do the magic. But since you defined one of the OneOf's types to be an interface, user-defined conversion won't work.

To make that work you can use a static methods that is defined on the OneOf&lt;T0,T1&gt; type:

return OneOf&lt;IEnumerable&lt;Item&gt;, Error&gt;.FromT0(Enumerable.Empty&lt;Item&gt;());

huangapple
  • 本文由 发表于 2023年7月7日 03:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定