英文:
OneOf return Enumerable.Empty<Item>()?
问题
如何使用C#的OneOf包返回Enumerable.Empty<ExchangeRate>()?
public async Task<OneOf<IEnumerable<ExchangeRate>, Error>> GetResults()
{
return OneOf<IEnumerable<ExchangeRate>, Error>.FromT0(Enumerable.Empty<ExchangeRate>());
}
错误:无法隐式转换类型'System.Collections.Generic.IEnumerable<Proj.ExchangeRate>'为'OneOf.OneOf<System.Collections.Generic.IEnumerable<Proj.ExchangeRate>, Proj.Error>'
是否有更好的方法?例如,创建一个具有默认值为Enumerable.Empty<Item>()
的NoResults
对象的Value
属性,然后将其包括在OneOf返回类型的列表中?
英文:
How to return Enumerable.Empty<ExchangeRate>() using the OneOf package for C#?
public async Task<OneOf<IEnumerable<Item>, Error>> GetResults()
{
return Enumerable.Empty<Item>(); // error
}
Error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Proj.Item>' to 'OneOf.OneOf<System.Collections.Generic.IEnumerable<Proj.Item>, Proj.Error>'
Is there a better approach? i.e. creating a new NoResults
object with a Value
property with a default value of Enumerable.Empty<Item>()
, and then include it in the list of OneOf return types?
答案1
得分: 2
首选方式是使用OneOf
定义的隐式转换运算符,所以你只需要返回一个值(就像你尝试过的那样),隐式转换运算符会自动处理。但是由于你将OneOf
的类型之一定义为接口,用户定义的转换将不起作用。
要使其起作用,你可以使用在OneOf<T0,T1>
类型上定义的静态方法:
return OneOf<IEnumerable<Item>, Error>.FromT0(Enumerable.Empty<Item>());
英文:
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<T0,T1>
type:
return OneOf<IEnumerable<Item>, Error>.FromT0(Enumerable.Empty<Item>());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论