c# generic self-referencing declarations

后端 未结 4 1094
面向向阳花
面向向阳花 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:31

    It is helpful, when you work with some external library or framework(which you can't or don't want modify). For example, you have class User from this library and definitely developer, who will use it, will define CustomUser class, which is inherited from it (just for adding some custom fields). Also let's imagine, that User class has some references to another users, for example: creator and deletor (which obviously will be instances of CustomUser type). And at this case generic self-referencing declaration can help very well. We will pass type of descendant(CustomUser) as parameter to base(User) class, so at User class declaration we can set types of creator and deletor exactly as they will be at future(CustomUser), so no casting will be needed:

    public class User where TCustomUser : User
    {
        public TCustomUser creator {get;set;}
        public TCustomUser deletor {get;set;}
    
        //not convenient variant, without generic approach
        //public User creator {get;set;}
        //public User deletor {get;set;}     
    }
    
    public class CustomUser : User
    {
        //custom fields:
        public string City {get;set;}
        public int Age {get;set;}
    }
    

    Usage:

    CustomUser customUser = getUserFromSomeWhere();
    //we can do this
    var creatorsAge = customUser.creator.Age;
    //without generic approach:
    //var creatorsAge = ((CustomUser)customUser.creator).Age;
    

提交回复
热议问题