【问题标题】:Casting object to Implemented Interfaces将对象转换为已实现的接口
【发布时间】:2017-01-31 03:24:09
【问题描述】:

我在将对象转换为实现的接口时遇到问题,跨不同的程序集,接口也使用泛型。

我有 3 个库。 合同(界面位置) 实现(接口实现) MainAssembly(恰好是一个 ASP.NET MVC5 应用程序)

主要参考合同和实施。实现引用合同。

Contracts 包含 2 个接口,一个使用另一个接口类型的泛型

public interface IConfig{}
public interface IStore<TConfig> where TConfig : IConfig{}

Implementations 包含 2 个类,它们像这样实现这些接口。

public class ConfigBase : IConfig {}
public class Store<TConfig> :IStore<TConfig> where TConfig : ConfigBase {}

ASP.NET 应用程序有一个继承自 ConfigBase 类的类

public class Configuration : ConfigBase {}

在合同库中,有一个服务类,它包含一个需要 IStore 类型的方法

public void DoSomething(IStore<IConfig> store){}

但是传入一种类型的 Store 告诉我它不能转换它。这是发生编译时错误的地方,一切似乎都可以正确构建。

Store<Configuration> store = new Store<Configuration>();
serviceObj.DoSomething(store);

【问题讨论】:

  • 为此,您需要在 IStore 中创建 TConfig 共变体。 msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx
  • 啊,谢谢,我只需要将 IStore 更改为 IStore
  • 请注意,只有在TConfig 仅用作输出(方法和只读属性的返回)而不是IStore 中的输入(方法参数和可写属性)时,您才应该这样做。跨度>

标签: c# generics interface casting


【解决方案1】:

使用out泛型修饰符使您成为通用接口协变

public interface IStore<out TConfig> where TConfig : IConfig{}.

【讨论】:

  • 感谢您的成功,准备做一些阅读以尝试完全理解我刚刚所做的。
猜你喜欢
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 2019-05-08
  • 2015-04-11
  • 2010-12-08
  • 1970-01-01
相关资源
最近更新 更多