将对象投射到实现的接口 [英] Casting object to Implemented Interfaces
问题描述
我在将一个对象转换为实现Interface时,遇到了一个问题,跨越不同的程序集,Interfaces也在使用泛型。
我有3个库。
Contracts(接口位置)
实现(接口实现)
MainAssembly(容易成为ASP.NET MVC5应用程序)
Main参考合同和实施。
合约包含2个接口,一个使用另一个接口类型的泛型
public interface IConfig {}
public interface IStore< TConfig> TConfig:IConfig {}
实现包含2个实现这些接口的类,如下所示。
public class ConfigBase:IConfig {}
public class Store< TConfig> :IStore< TConfig>其中TConfig:ConfigBase {}
ASP.NET应用程序有一个继承自ConfigBase类的类
public class配置:ConfigBase {}
在合同库中,有一个服务类,它包含一个需要一种类型的IStore的方法
public void DoSomething(IStore< IConfig> store){}
商店告诉我它不能转换它。这是发生编译时错误的地方,所有appeasrs都可以正确地构建。
Store< Configuration> store = new Store< Configuration>();
serviceObj.DoSomething(store);
使通用接口协变使用 out
通用修饰符
public interface IStore< out TConfig> TConfig:IConfig {}。
I'm having a problem with Casting an object to it's implemented Interface, across different assemblies, the Interfaces are also using Generics.
I have 3 libraries. Contracts (Interface Location) Implementations (Interface Implementations) MainAssembly (Happens to be an ASP.NET MVC5 application)
Main references Contracts and Implementations. Implementations references Contracts.
Contracts Contains 2 Interfaces, one uses a generic that is of the other Interface type
public interface IConfig{}
public interface IStore<TConfig> where TConfig : IConfig{}
Implementations Contains 2 Classes that Implements these Interfaces like so.
public class ConfigBase : IConfig {}
public class Store<TConfig> :IStore<TConfig> where TConfig : ConfigBase {}
ASP.NET application Has a Class that Inherits from the ConfigBase class
public class Configuration : ConfigBase {}
Within the Contracts Library, there is a Service Class, that contains a Method that Requires a type of IStore
public void DoSomething(IStore<IConfig> store){}
However Passing in a type of Store is telling me it can't convert it. This is where the compile time error occurs, everything appeasrs to build correctly.
Store<Configuration> store = new Store<Configuration>();
serviceObj.DoSomething(store);
Make you generic interface covariant using out
generic modifier
public interface IStore<out TConfig> where TConfig : IConfig{}.
这篇关于将对象投射到实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!