在接口中包括一个通用类型参数,由接口约束
我被限制在接口约束的实现上。我的用法对我是直觉的,但没有编译,所以我误解了一些东西。
我的接口:
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);
}
}
实例上下文
引发错误:
参数1:无法从“上下文”转换为'iContext&lt; ifoobar&gt;'
如何约束通用类型参数以便可以使用我的实现?
I am stuck on the usage of an implementation that is constraint by an interface. My usage is intuitive to me, but does not compile so I am misunderstanding something.
My interfaces:
interface IEntity
{
int ExampleMethod(IContext<IFooBar> context);
}
interface IContext<T> where T : class, IFooBar
{
T FooBar { get; set; }
}
interface IFooBar
{
int Value { get; }
}
My implementations:
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; } }
}
Usage of Entity class, where problem is thrown
class UsageOfEntity
{
public UsageOfEntity()
{
var context = new Context();
var entity = new Entity();
int result = entity.ExampleMethod(context);
}
}
The usage of instance context
throws an error:
Argument 1: cannot convert from 'Context' to 'IContext<IFooBar>'
How do I constrain the generic type parameter such that my implementation can be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上下文
是icontext&lt; foobar&gt;
不是icontext&lt; ifoobar&gt;
。因为op在注释中指出
icontext&lt; t&gt; .foobar
仅需要仅阅读,所以t
可以使得协变量:现在,因为
foobar
实现ifoobar
,使用icontext&lt; foobar&gt;
代替icontext&lt; ifoobar&gt;
::Context
is anIContext<FooBar>
not anIContext<IFooBar>
.Because the OP has indicated in the comments that
IContext<T>.FooBar
only needs to be read-only,T
can be made covariant:Now, because
FooBar
implementsIFoobar
, it is valid to use aIContext<FooBar>
in place of aIContext<IFooBar>
:代码中的问题是,您正在尝试将
上下文
转换为type
icontext 就像您的错误告诉您一样。您正在尝试将
上下文
传递给icontext
在此行中,您应该在
type
中传递exipplemethod()
< 代码>上下文&lt; foobar&gt; 。我还想指出,为
poco
类制作界面是不必要的,只需保持正常的类即可。您的代码应该看起来像这样:
The problem in your code is that you are trying to convert
Context
toType
IContext
just as your error tells you.You are trying to pass
Context
toIContext
in this lineYou should make the
Type
passed inExampleMethod()
Context<FooBar>
.I would also like to point out that making an interface for a
POCO
class is unnecessary, just keep it a normal class.Your code should look like this: