What are the good reasons to wish that .NET generics could inherit one of the generic parameter types?

后端 未结 8 1425
旧时难觅i
旧时难觅i 2020-12-06 04:40

This post is in continuation of this one.

I am trying to understand if I am the only one who misses and needs the ability of a .NET generic type to inherit one of it

8条回答
  •  囚心锁ツ
    2020-12-06 05:26

    The basic rule of generics that prevents this is "the content of a generic type must be well-defined on the generic argument." Lets look at how this applies to the following code:

    public abstract class AbstractBase
    {
        public abstract string MyMethod();
    }
    
    public class SomeType : T
    {
    }
    
    public class SomeUsage
    {
        void Foo()
        {
            // SomeType does not implement AbstractBase.MyMethod
            SomeType b = new SomeType();
        }
    }
    

    So we try to implement MyMethod():

    public class SomeType : T
    {
        public override string MyMethod()
        {
            return "Some return value";
        }
    }
    
    public class SomeUsage
    {
        void Foo()
        {
            // SomeType does not inherit a virtual method MyMethod()
            SomeType b = new SomeType();
        }
    }
    

    So lets make a requirement that T be derived from AbstractBase:

    public abstract class DerivedAbstractBase : AbstractBase
    {
        public abstract string AnotherMethod();
    }
    
    public class SomeType : T
        where T : AbstractBase
    {
        public override string MyMethod()
        {
            return "Some return value";
        }
    }
    
    public class SomeUsage
    {
        void Foo()
        {
            // SomeType does not implement DerivedAbstractBase.AnotherMethod()
            SomeType b = new SomeType();
        }
    }
    

    Summary:

    By the time you account for all the restrictions in base types, you're so constrained that deriving from a generic parameter is pointless.

提交回复
热议问题