【问题标题】:c# return interface type from methodc# 从方法返回接口类型
【发布时间】: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&lt;Foo&gt; 兼容。
  • 感谢@RobertHarvey 和Netmage 非常感谢,我认为我在正确的轨道上。请查看我的返回类型不正确的行。
  • “其中 TItem 可以是 Foo 类型或 Bar 类型”……由……实现者或调用者决定?
  • 您应该返回一个EnumAndDispose&lt;T&gt;,其中T 是Foo。

标签: c# generics interface


【解决方案1】:

您的代码可能看起来相似吗? 我试图从提供的错误消息中得出它...

public IEnumerableDisposable<TItem> GetItems<TItem>()
{
    var foo = new EnumandDisposeFoo(_pagedApi);
    // var fooitems  = foo.GetEnumerator(); // not used and is in fact of type `IEnumerator<Foo>`
    return foo;
}

如果是,EnumandDisposeFoo 实现IEnumerableDisposable&lt;T&gt;,同时将元素类型T 指定为Foo。在这一点上,它不再是通用的。尝试将 (隐式) 强制转换为通用 IEnumerableDisposable&lt;TItem&gt; 将失败,除非您为该特定隐式强制转换提供覆盖。

我怀疑你想要那个。

要么将EnumandDisposeFoo 更改为通用实现:

public class EnumandDisposeFoo<TItem> : IEnumerableDisposable<TItem> { }

或者您将方法限制为返回(非通用)IEnumerableDisposable&lt;Foo&gt;。

编译器不知道你想返回哪种类型,因此编译时不会出错。 用GetItems&lt;Foo&gt;() 调用你的方法可能会成功。 但是使用Foo 之外的任何其他类型调用您的方法TItem 将在运行时尝试隐式转换,这可能会或可能不会失败。

【讨论】:

    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2016-03-15
    • 2017-05-15
    相关资源
    最近更新 更多