基于接口设计的C#泛型方法

C# generic method based on interface design

有一个 class 作为基础:

public abstract class DataObjectEntityItemBase
{ }

派生 class:

public class CatalogDataObjectEntityItem : DataObjectEntityItemBase, ISupportsTabularDataObjectEntityContainer
{ }

有个方法:

internal void FetchTabSectionDataObjectEntityByParentItem<T1>(
               ITabSectionManager dataObjectEntityContainerOwner, 
               T1 parentDataObjectEntityItem)                                                                                                                             
where T1 : DataObjectEntityItemBase, ISupportsTabularDataObjectEntityContainer
{ }

我想调用的问题代码FetchTabSectionDataObjectEntityByParentItem:

FetchTabSectionDataObjectEntityByParentItem(
       refDoeItem.LinkedConfigurationObject as ITabSectionManager, 
       refDoeItem as ISupportsTabularDataObjectEntityContainer);

错误:

Error CS0311 The type ISupportsTabularDataObjectEntityContainer cannot be used as type parameter 'T1' in the generic type or method FetchTabSectionDataObjectEntityByParentItem(ITabSectionManager, T1)'. There is no implicit reference conversion from ISupportsTabularDataObjectEntityContainer DataObjectEntityItemBase refDoeItem is variable as DataObjectEntityItemBase type.

refDoeItemDataObjectEntityItemBase.

类型的变量

约束是编译时期间的一种机制,它保证必须调用的运算符或方法将受到客户端代码可能指定的任何类型参数的支持。

在您的情况下,约束 where T1 : DataObjectEntityItemBase, ISupportsTabularDataObjectEntityContainer 意味着实例应从 DataObjectEntityItemBase 派生并同时实现 ISupportsTabularDataObjectEntityContainer

通过将 refDoeItem 不必要地转换为 ISupportsTabularDataObjectEntityContainer,您违反了这条规则。只需删除演员表,一切都会根据您定义的约束自动解决。但是如果你需要将它转换为另一种类型(例如 refDoeItem 是一个对象)你应该将它转换为符合整个约束的类型,在你的情况下是 CatalogDataObjectEntityItem .