Generics C # .net

In the code below "where T: WsgTypes.RouteRestriction" you can add several classes so that T can be only those few types of classes that interest me

    public static T GetDetails<T>(string code) where T : WsgTypes.RouteRestriction
    {
        T details;
        if (typeof(T) == typeof(WsgTypes.TicketType))
        {
            details = TicketTypeDetail.GetDetails(code) as T;

        }
        else if (typeof(T) == typeof(WsgTypes.RouteRestriction))
        {
            details = RouteRestrictionDetail.GetDetails(code) as T;

        }
        else
        {
            throw new NotSupportedException("");
        }
        return details;
        throw new NotImplementedException();
    }
+3
source share
6 answers

For inheritance, you can have one class with several interfaces.

public static T GetDetails<T>(string code) where T : WsgTypes.RouteRestriction, , IComparable
    {
    }

Instead, you can have an interface and have several classes implementing it.

public interface IInterface
    {}

    public class Class1: IInterface
    {}

    public class Class2: IInterface
    {}

public static T GetDetails<T>(string code) where T:IInterface
        {
            T instance;
            // ...
            return instance;
        }
+1
source

It seems to me that this is not the correct use of generics. It would be better if TicketTypeand RouteRestrictionimplemented some IDetailed.

+5
source

, .

, "", " ".

, , , .

+4

, . - , , , . , , .

, . . .

, typeof is as.

+1

. ...

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

... constaints. , - , .

Here is an example of several limitations (from the above):

class Base { }
class Test<T, U>
    where U : struct
    where T : Base, new() { }
+1
source

You tried to separate them as follows:

public static T GetDetails<T>(string code) where T : WsgTypes.RouteRestriction, NextClass, AnotherClass, AndSoOn
{
...
}
0
source

Source: https://habr.com/ru/post/1708638/


All Articles