jeudi 15 mai 2014

c# - contraintes sur les paramètres de type - où t: classe - Stack Overflow


I have problem with constraints, because I want, that the type argument is a reference type just one of 3 classes, not the any others, so constraint "where L: class" is not ok.


Here is example:


public class MyClass <L> 
where L : Circle
where L: Rectangle
where L: Triangle

This mean, that must comply with all constraints. Unfortunately, I have not found the answer yet.


Thank you very much.




You should create a base class or interface that Circle, Rectangle, and Triangle inherit from.


For example:


interface IShape
{
}

class Circle : IShape
{
// ...
}

class Rectangle : IShape
{
// ...
}

class Triangle : IShape
{
// ...
}

Then do the constraint on IShape:


public class MyClass <L> 
where L : IShape


I have problem with constraints, because I want, that the type argument is a reference type just one of 3 classes, not the any others, so constraint "where L: class" is not ok.


Here is example:


public class MyClass <L> 
where L : Circle
where L: Rectangle
where L: Triangle

This mean, that must comply with all constraints. Unfortunately, I have not found the answer yet.


Thank you very much.



You should create a base class or interface that Circle, Rectangle, and Triangle inherit from.


For example:


interface IShape
{
}

class Circle : IShape
{
// ...
}

class Rectangle : IShape
{
// ...
}

class Triangle : IShape
{
// ...
}

Then do the constraint on IShape:


public class MyClass <L> 
where L : IShape

0 commentaires:

Enregistrer un commentaire