【发布时间】:2018-12-20 23:18:26
【问题描述】:
我有 2 个这样定义的接口
public interface IEnumerableDisposable<out T> : IEnumerable<T>, IDisposable
{
}
public interface IApiCollection
{
IEnumerableDisposable<TItem> GetItems<TItem>();
}
还有一个方法需要像这样返回第一个接口类型
public IEnumerableDisposable<TItem> GetItems<TItem>()
其中 TItem 可以是 Foo 类型或 Bar 类型
问题我如何将返回类型转换为 IEnumerableDisposable ?
我的理解是我需要上课
public class EnumandDisposeFoo : IEnumerableDisposable<Foo>
{
}
并在我的方法中实例化这个类。然后我将如何将类型转换回其通用形式?
任何帮助将不胜感激
var foo = new EnumandDisposeFoo(_pagedApi);
var fooitems = foo.GetEnumerator();
return foo; --> errors with
Cannot implicitly convert type 'ApiCollection.Implementation.EnumandDisposeFoo' to 'ApiCollection.IEnumerableDisposable<TItem>'. An explicit conversion exists (are you missing a cast?
【问题讨论】:
-
您不需要“将类型转换回其通用形式”。只需返回您的
EnumandDisposeFoo实例;它已经实现了你返回的接口。 -
您不必转换为通用形式 - 您根本不需要转换,
EnumandDisposeFoo的赋值应该与IEnumerableDisposable<Foo>兼容。 -
感谢@RobertHarvey 和Netmage 非常感谢,我认为我在正确的轨道上。请查看我的返回类型不正确的行。
-
“其中 TItem 可以是 Foo 类型或 Bar 类型”……由……实现者或调用者决定?
-
您应该返回一个
EnumAndDispose<T>,其中T是Foo。