1
public abstract class BaseDocumentLayer : IDocumentLayer
{                                                       
   public IDocumentLayer NextLayer { get;set;}

   public virtual Document<T, U> ProcessDocument<T, U>(Document<T, U> document) {
      if(NextLayer != null)
         document = NextLayer.ProcessDocument(document);
      return document;          
   }
}

public override Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> ProcessDocument<GenericDatabaseDTO, GenericDatabaseConstants.ActionType>(Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> document)
{       
    return base.ProcessDocument<GenericDatabaseDTO, 
}

public static class GenericDatabaseConstants 
{    
    public enum ActionType 
    {                
       CreateGeneric,
       ReadGeneric,
       UpdateGeneric,
       DeleteGeneric,               
    }
}

为什么会出现错误:类型参数声明必须是标识符而不是类型?

在此处输入图像描述

错误1:

public override Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> ProcessDocument(Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> document)
{   

    return base.ProcessDocument(document);
}

错误 1 ​​'GenericDocumentLayer2.Document.GenericDatabase.ProcessLayer.ProcessDocument(GenericDocumentLayer2.TypeDefinition.Document)':找不到合适的方法来覆盖

我没有更改我的原始 BaseLayer.ProcessDocument 方法

更新

public void Add(GenericDatabaseField field) {
            var dto = new GenericDatabaseDTO();
            dto.Field = field;
            dto.Id = "test";

            var document = new Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType>(dto, GenericDatabaseConstants.ActionType.CreateGeneric, null);
            IDocumentLayer layer = DocumentFactory.CreateDocumentLayers();
                                          // The generic ProcessDocument is never called just the base version
        document = layer.ProcessDocument<GenericDatabaseDTO, GenericDatabaseConstants.ActionType>(document);                
    }
4

1 回答 1

1

您不能覆盖特定类型的泛型方法。这对于 C++ 的模板是可能的,但对于 C# 的泛型则不行。

要编译您的代码,请将其更改为:

public override Document<TDTO, TActionType> ProcessDocument<TDTO, TActionType>(Document<TDTO, TActionType> document) 

这将编译,但它将覆盖所有泛型参数的基类型方法。

如果你想为一种类型提供一个特殊的实现,你可以添加一个非泛型重载并在特殊处理之后在内部调用泛型版本:

public Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> ProcessDocument(Document<GenericDatabaseDTO, GenericDatabaseConstants.ActionType> document)  
{
    // some special handling for this special case here...

    return base.ProcessDocument(document);
}

但是,请注意,这将在像这样的多态场景中中断:

假设上述方法在Derived. Derived来源于Base

GenericDatabaseDTO dto = /*...*/;
GenericDatabaseConstants.ActionType actionType = /*...*/;

Derived d = new Derived();
Base b = d;

// calls the non-generic version with special handling from Derived:
d.ProcessDocument(dto, actionType);
// calls the generic version from Base:
b.ProcessDocument(dto, actionType);
于 2012-08-28T10:33:33.410 回答