Generic Interface inheriting Non-Generic One C#

前端 未结 3 1367
无人及你
无人及你 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:45

    The runtime treats IRestriction and IRestriction as different distinct classes (they even have their own set of static variables). In your case the only classes common to both IRestriction and IRestriction in the inheritance hierarchy are IRestriction and object.

    So indeed, having a list of IRestriction is the only sensible way to go.


    As a side note: you have a property Limit in there that you might want to access regardless of whether you're dealing with an IRestriction or IRestriction. What I would do in this case is to define another property object Limit { get; } on IRestriction, and hide it in the actual implementation. Like this:

    public interface IRestriction
    {
        object Limit { get; }
    }
    
    public interface IRestriction : IRestriction
        where T : struct
    {
        new T Limit { get; set; }
    }
    
    public class TimeRestriction : IRestriction
    {
        public TimeSpan Limit { get; set; }
    
        // Explicit interface member:
        // This is hidden from IntelliSense
        // unless you cast to IRestriction.
        object IRestriction.Limit
        {
            get
            {
                // Note: boxing happens here.
                return (object)Limit;
            }
        }
    }
    

    This way you can access Limit as object on all your IRestriction when you don't care what type it is. For example:

    foreach(IRestriction restriction in this.Restrictions)
    {
        Console.WriteLine(restriction.Limit);
    }
    

提交回复
热议问题