[英]Inheriting from class with type constraints - “There is no implicit reference conversion from…”
I have a base class for databinding a single datasource like this: 我有一个用于对单个数据源进行数据绑定的基类,如下所示:
public abstract class DataControlBase<TContainer, TDataType> : Control
where TDataType : new()
where TContainer : TemplateContainerBase<TDataType>, new()
{
public TDataType DataSource { get; set; }
}
The container class (TContainer) will always inherit from the container base: 容器类(TContainer)将始终从容器基类继承:
public abstract class TemplateContainerBase<TDataType> : Control
where TDataType : new()
{
public TemplateContainerBase() { }
public TDataType DataItem { get; set; }
}
Finally I have a repeater base where I will bind several data items as the datasource: 最终,我有了一个转发器基础,我将在其中绑定几个数据项作为数据源:
public abstract class RepeaterBase<TContainer, TDataType> : DataControlBase<TContainer, List<TDataType>>
where TDataType : new()
where TContainer : TemplateContainerBase<TDataType>, new()
{
}
I get an error on the RepeaterBase saying this 我在RepeaterBase上收到一个错误,说这
Error 1 The type 'TContainer' cannot be used as type parameter 'TContainer' in the generic type or method 'WebTestHarness.Controls.DataControlBase'.
错误1类型'TContainer'不能用作通用类型或方法'WebTestHarness.Controls.DataControlBase'中的类型参数'TContainer'。 There is no implicit reference conversion from 'TContainer' to 'WebTestHarness.Controls.TemplateContainerBase>'.
没有从'TContainer'到'WebTestHarness.Controls.TemplateContainerBase>'的隐式引用转换。
I have read a few different threads describing similar issues but all seem to relate to methods whereas this is solely to do with class design. 我已经阅读了一些描述类似问题的不同线程,但似乎都与方法有关,而这仅与类设计有关。
You have 你有
RepeaterBase<TContainer, TDataType> : DataControlBase<TContainer, List<TDataType>>
so you've set List<TDataType>
as the second type parameter Y
for DataControlBase<X, Y>
. 因此,您已将
List<TDataType>
设置为DataControlBase<X, Y>
的第二个类型参数Y
But your constraint for DataControlBase
requires that X : TemplateContainerBase<Y>, new()
. 但是您对
DataControlBase
的约束要求X : TemplateContainerBase<Y>, new()
。 So, in your case, you would need the constraint 因此,在您的情况下,您将需要约束
where TContainer : TemplateContainerBase<List<DataType>>, new()
on TContainer
, not 在
TContainer
,不是
where TContainer : TemplateContainerBase<DataType>, new()
as you currently have. 如您目前所拥有的。
That is, just because you've used the same names for the type parameters in the varying classes does not mean that they represent the same types when you start parameterizing things. 也就是说,仅仅因为您在不同的类中为类型参数使用了相同的名称 ,并不意味着在开始对事物进行参数化时它们表示相同的类型。 That is
那是
class Foo<A> { }
class Bar<A> : Foo<List<A>> { }
The A
in Bar
is not the same as the A
in Foo
. 在
A
在Bar
不一样的A
中Foo
。 Instead, List<A>
is playing the role of A
for Foo<A>
in the definition of Bar<A>
. 相反,在
Bar<A>
的定义中, List<A>
在Foo<A>
中扮演A
的角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.