Generic Interface inheriting Non-Generic One C#

前端 未结 3 1373
无人及你
无人及你 2020-12-09 16:18

This is class design question.

I have main abstract class

public abstract class AbstractBlockRule
{
    public long Id{get;set;}
    public abstract         


        
3条回答
  •  情歌与酒
    2020-12-09 16:42

    Your approach is typical (for example, IEnumerable implements IEnumerable like this). If you want to provide maximum utility to consumers of your code, it would be nice to provide a non-generic accessor on the non-generic interface, then hide it in the generic implementation. For example:

    public abstract class AbstractBlockRule
    {
        public long Id{get;set;}
        public abstract List Restrictions { get; set; }
    }
    
    public interface IRestriction
    {
        object Limit { get; }
    }
    
    public interface IRestriction : IRestriction 
        where T:struct
    {
        // hide IRestriction.Limit
        new T Limit {get;} 
    }
    
    public abstract class RestrictionBase : IRestriction
        where T:struct
    {
        // explicit implementation
        object IRestriction.Limit
        {
            get { return Limit; }
        }
    
        // override when required
        public virtual T Limit { get; set; }
    }
    
    public class TimeRestriction : RestrictionBase
    {
    }
    
    public class AgeRestriction : RestrictionBase
    {
    }
    
    public class BlockRule : AbstractBlockRule
    {
        public override List Restrictions { get; set; }
    }
    

    I also showed using a base restriction class here, but it is not required.

提交回复
热议问题