简体   繁体   中英

Returning generic types in c#

public class Manager<T> where T: IBallGame
{
T GetManager()
{
//if T is ISoccer return new Soccer()
//if T is IFootball return new Football()

//This wont work. Why?
if (typeof(T) == typeof(ISoccer))
                return new Soccer();
}
}

Interface ISoccer: IBallgame
{
}
class Soccer: ISoccer
{
}
Interface IFootball: IBallgame
{
}
class Football:IFootball
{
}

I have already checked out this question How do I make the return type of a method generic? . Is there something more elegant than Convert.ChangeType()?

Why is it not possible to return an instance of Soccer or Football when there is a constraint on the type?

If you expect different implementations based on the exact type of the generic, you're not actually dealing with a generic any more.

You should define two classes, eg FootBallManager : Manager<IFootball> and SoccerManager : Manager<ISoccer>

Based on your update, what you actually want is an additonal constraint on your generic of new() and to implement your class as

public class Manager<T> where T: IBallGame, new()
{
    T GetManager()
    {
         return new T();         
    }
}
public class Manager<T> where T : class, IBallgame
{
    T GetManager()
    {
        //if T is ISoccer return new Soccer()
        //if T is IFootball return new Football()


        if (typeof(T) == typeof(ISoccer))
            return new Soccer() as T;

        //code
    }
}

public interface IBallgame
{

}
public interface ISoccer : IBallgame
{
}
public class Soccer : ISoccer
{
}
public interface IFootball : IBallgame
{
}
class Football : IFootball
{
}

You just need a class constraint and as T

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