简体   繁体   中英

implementing abstract class using derived types

this may be somewhere else under generic types but I cant seem to follow a lot of the answers. Apologies if this is a repeat of another question.

the following code is for a three layer app with Data, Logic and Presentation Layers

in my data layer I have a Collection of entitys and a base entity

public abstract class BaseEntity
{
    int LastModifiedBy { get; set; }
    DateTime LastModifiedDate{get;set;}
}


public partial class DocNum: BaseEntity
{   
}

public partial class DataList: BaseEntity
{   
}

in my logic layer I have a BaseDTO class for transferring data. here is the code for it

public abstract class BaseDTO
{    
    protected abstract void ConvertFromEntity(BaseEntity entity);
    public abstract void ConvertToEntity();
}

I then go and create the implementation class DocNum based on it as follows

public class DTODocNum : BaseDTO
{
    //properties here

    public DTODocNum()
    {
    }

    public DTODocNum(DocNum entity)
    {
        ConvertFromEntity(entity)
    }

    protected override void ConvertFromEntity(DocNum entity)
    {
        throw new NotImplementedException();
    }

    public override void ConvertToEntity()
    {
        throw new NotImplementedException();
    }
}

however this will not compile telling me that no suitable method to override was found. I know I can do the following but I want thhis method to only accept a DocNum entity from the Data Layer:

    protected override void ConvertFromEntity(BaseEntity entity)
    {
        throw new NotImplementedException();
    }

I have also tried generic types with the following

public abstract class BaseDTO
{
    protected abstract void ConvertFromEntity<T>(T entity);
    public abstract T ConvertToEntity<T>();        
}        

and the following in the derived class:

protected override void ConvertFromEntity<T>(T entity) where T:DocNum
{
    throw new NotImplementedException();
}

but now the error given is Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly

Can any one help me implement this solution so that the DTODocNum can compile whilst referring to the entity type?

Move the type parameter to the class level and add a constraint:

public abstract class BaseDTO<T> where T : BaseEntity
{
    protected abstract void ConvertFromEntity(T entity);
    public abstract T ConvertToEntity();
}

public class DTODocNum : BaseDTO<DocNum> { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM