[英]Including a generic type parameter in interface, constraint by an interface
我堅持使用受接口約束的實現。 我的用法對我來說很直觀,但沒有編譯,所以我誤解了一些東西。
我的界面:
interface IEntity
{
int ExampleMethod(IContext<IFooBar> context);
}
interface IContext<T> where T : class, IFooBar
{
T FooBar { get; set; }
}
interface IFooBar
{
int Value { get; }
}
我的實現:
class Entity : IEntity
{
public int ExampleMethod(IContext<IFooBar> context)
{
return context.FooBar.Value;
}
}
class Context : IContext<FooBar>
{
public FooBar FooBar { get; set; }
}
class FooBar : IFooBar
{
public int Value { get { return 10; } }
}
引發問題的實體類的用法
class UsageOfEntity
{
public UsageOfEntity()
{
var context = new Context();
var entity = new Entity();
int result = entity.ExampleMethod(context);
}
}
使用實例context
會拋出錯誤:
參數 1:無法從 'Context' 轉換為 'IContext<IFooBar>'
如何約束泛型類型參數以便可以使用我的實現?
Context
是IContext<FooBar>
而不是IContext<IFooBar>
。
因為OP在評論中指出IContext<T>.FooBar
只需要是只讀的,所以可以使T
成為協變的:
interface IContext<out T>
where T : class, IFooBar
{
T FooBar { get; }
}
現在,因為FooBar
實現IFoobar
,所以使用IContext<FooBar>
代替IContext<IFooBar>
<IFooBar> 是有效的:
您的代碼中的問題是您正在嘗試將Context
轉換為Type
IContext
正如您的錯誤所告訴您的那樣。
{
public UsageOfEntity()
{
var context = new Context();
var entity = new Entity();
int result = entity.ExampleMethod(context);
}
}
您正在嘗試在這一行中將Context
傳遞給IContext
entity.ExampleMethod(context);
您應該在ExampleMethod()
Context<FooBar>
中傳遞Type
。 我還想指出,為POCO
類創建接口是不必要的,只需將其保留為普通類即可。
您的代碼應如下所示:
class Entity : IEntity
{
public int ExampleMethod(Context<FooBar> context)
{
return context.FooBar.Value;
}
}
interface IEntity
{
int ExampleMethod(IContext<IFooBar> context);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.