简体   繁体   中英

Type Constraints on Generics C# - Multiple Constraints

I have a class that contains a two sets of data.

  1. A list of values for X.
  2. A list of values for Y.

Now, X and Y could hold either a string/double/integer/datetime in any possible combination. The only rule being that at any given point of time, both lists must contain equal number of values.

I could solve the problem of always holding equal data by providing access only through an AddXY method and a RemoveAt method (ensuring that at any given point of time, I can guarantee that both the X List and Y List are equally sized).

Further, I'd like the end user of this class to be able to access the X and Y values through indexers as shown below.

someClassInstance.X[i] and someClassInstance.Y[i]

Since, there are no options for this in C#, I have opted for exposing X and Y as IList (AsReadOnly) method.

Now, I considered the idea of constraining the types by using Generics. But I am unable to find appropriate examples for this particular case.

How do I say

public class MyClass<P, Q> 
     where P : Double, String, Integer, DateTime 
     and Q : Double, String, Integer, DateTime

Should I discard the idea altogether and look at some kind of Tuple or some such data structure?

EDIT: I also know that the constraints cannot be Value Types, so how does this work?

What you are asking is not possible in C#. There is no generic type constraint that unifies these types.

The best you can do is check at runtime, for example in the static constructor. Something like this:

public class MyClass<P, Q>
{
    static MyClass() 
    {
       if (IsValidType(typeof(P) 
           && IsValidType(typeof(Q))
       throw new NotSupportedException("invalid type for MyDataStructure");
    }
    static bool IsValidType(Type type)
    {
       // logic to check whether type is acceptable
       return true;
    }
}

However I'd advise against this since it seems somewhat artificial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM