Using a generic method instead of a method parameter

I use a framework that has this method

public static void Initialize<T>() where T : Game;

and in the code example, you enter your game like this:

TargetDevice.Initialize<MyGame>();

I am wondering what are the benefits of using an initialization style

public static void Initialize<T>() where T : Game;
TargetDevice.Initialize<MyGame>();

instead

public static void Initialize(Game game);
TargetDevice.Initialize(new MyGame());

Is this common style of the initialization method has any name that I can read? Why should I choose one style instead of another?

Thank.

+3
source share
1 answer

If you mean the difference between:

Foo<T>()

and

Foo(Type type)

then there are virtues of both. The latter is much more convenient when using reflection to load types (maybe your types Gamecome from plugins?) - generics and reflection do not mix very conveniently.

, ; .., . , T, , Comparer<T>.Default EqualityComparer<T>.Default (: ) - , , .

, T : Game, ( , Game - , ). ; a List<Game> , List<T> ( T : Game), .

, , , :

void Foo<T>() where T : Game
{
    Foo(typeof(T));
}
void Foo(Type type) {...}

- , Activator.CreateInstance(type) new T() - T : ISomeInterface. , .

+5

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


All Articles