【发布时间】:2015-04-16 11:36:28
【问题描述】:
我有以下概念模型:
public interface IFoo<out T>
{
T Data { get; }
}
public struct Foo<T> : IFoo<T>
{
public Foo(T data) : this()
{
Data = data;
}
public T Data { get; private set; }
}
public class FooService<T>
{
...
public Foo<T> Get(string id)
{
...
}
}
然后我尝试以一种在概念上与此等效的方式使用它:
// Create and register a few FooService instances
ServiceLocator.Register(new FooService<DateTime>(), "someServiceId");
ServiceLocator.Register(new FooService<double?>(), "anotherServiceId");
// Retrieve a particular FooService instance and call the Get method
var fooService = (FooService<object>)ServiceLocator.Get("someServiceId");
var foo = fooService.Get("someFooId");
我想在 FooService 实例上使用 Get() 方法 - 无论所选 FooService 实例返回什么类型。但是,此代码会导致以下异常:
无法将“WindowsFormsApplication7.FooService`1[System.DateTime]”类型的对象转换为“WindowsFormsApplication7.FooService`1[System.Object]”类型。
任何有关如何解决此问题的建议将不胜感激。
您可能会争论,为什么我首先将 FooService 设为通用。但是,这样做是为了在类型安全的环境中确保类型安全。但是,在这种特殊情况下,FooService 应在 Web API 控制器中用于服务各种类型的 Foo。无论 T 的类型如何,它都会返回一个带有 T 的 Foo 的响应。
【问题讨论】:
-
你还需要一个接口 IFooServive
,你的演员表是 (IFooService
标签: c# generics covariance