Restricting T to string and int?

前端 未结 7 1458
悲哀的现实
悲哀的现实 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:53

    Given that you only have two types here I would go down an OO route here instead and just have two classes for the two types.

    Generics are best used where the circumstances in which they can be applied are, you know, generic. They're a lot less use in circumstances like this.

    You can restrict to struct or class types only, and I do think that there need to be numeric or operator based restrictions (e.g. must support +=)

    Int and string are really quite different, certainly more different than int and double. It wouldn't make much sense for a generic class to support the immutable reference type of string and the value type of int without also supporting other types more similar to either of them.

    0 讨论(0)
  • 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 <T> { }
    
    public class StringStatisticItemHits : StatisticItemHits<string> { }
    
    public class IntegerStatisticItemHits : StatisticItemHits<int> { }
    

    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 <T> : IStaticticItemHits { }
    
    public interface IStatisticItemHits { }
    
    0 讨论(0)
  • 2020-12-16 12:58

    Simply use:

    where TSource : IEquatable<string>
    
    0 讨论(0)
  • 2020-12-16 13:06

    Not possible to do this with 'where'. You can't do an 'or'.

    0 讨论(0)
  • 2020-12-16 13:17

    The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that inherit from int and string, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?

    0 讨论(0)
  • 2020-12-16 13:17

    You could make StatisticItemHits<T> an abstract class and create two subclasses:

    StatisticItemHitsInt : StatisticItemHits<int>{}

    StatisticItemHitsString : StatisticItemHits<string>{}

    That way there can only be an int and string-representation of StatisticItemHits

    0 讨论(0)
提交回复
热议问题