c# generic self-referencing declarations

后端 未结 4 1118
面向向阳花
面向向阳花 2020-12-08 07:53

I\'ve been reading Albaharis\' \"C# 5.0 in A Nutshell\" and I\'ve encountered this in Generics section and it is said to be legal:

class Bar where T         


        
4条回答
  •  清歌不尽
    2020-12-08 08:45

    It means that T must inherit from Person.

    This is a typical way to create type-specific methods or properties or parameters in the base class, specific to the actual descendant.

    For instance:

    public abstract class Base where T : Base, new()
    {
        public static T Create()
        {
            var instance = new T();
            instance.Configure(42);
            return instance;
        }
    
        protected abstract void Configure(int value);
    }
    
    public class Actual : Base
    {
        protected override void Configure(int value) { ... }
    }
    
    ...
    
     Actual a = Actual.Create(); // Create is defined in Base, but returns Actual
    

提交回复
热议问题