Restricting T to string and int?

前端 未结 7 1462
悲哀的现实
悲哀的现实 2020-12-16 12:17

I have built myself a generic collection class which is defined like this.

public class StatisticItemHits{...}

This class can be

7条回答
  •  北海茫月
    2020-12-16 12:54

    As others have said, you cannot use type restrictions in this way. What you can do is to specialise from your base type as follows:

    public class StatisticItemHits  { }
    
    public class StringStatisticItemHits : StatisticItemHits { }
    
    public class IntegerStatisticItemHits : StatisticItemHits { }
    

    Also, as your base class is generic, you won't be able to use this to polymorphically. If you need to do this make StatisticItemHits implement an interface and use this to reference instances. Something like:

    public class StatisticItemHits  : IStaticticItemHits { }
    
    public interface IStatisticItemHits { }
    

提交回复
热议问题