using generic method instead of method parameter
I am using a framework that has this method
public static void Initialize<T>() where T : Game;
and in sample code you intialize your game like this
TargetDevice.Initialize<MyGame>();
I am wondering what are benefits of using style of initialization
public static void Initialize<T>() where T : Game;
TargetDevice.Initialize<MyGame>();
instead of
public static void Initialize(Game game);
TargetDevice.Initialize(new MyGame());
Is that generic style of initializing method has any name that I can read of? Why should I choose one style inste开发者_如何学Pythonad of another?
Thanks.
If you mean the difference between:
Foo<T>()
and
Foo(Type type)
then there are merits of both. The latter is much more convenient when using reflecting to load the types (maybe your Game
types come from plugins?) - generics and reflection don't mix very conveniently.
The generic version is handy when everything is known at compile-time; you can add additional validation via constraints etc, which are enforced by the compiler. It can also be handy if you specifically want to use the T
, for example to use generic comparisons via Comparer<T>.Default
or EqualityComparer<T>.Default
(emphasis: these are just examples) - which accesses many common patterns, while avoiding things like boxing where appropriate.
In your case, since the T : Game
, boxing isn't an issue (I'm assuming Game
is a class, not an interface). You could go either way; a List<Game>
will work almost as well as the slightly more specific List<T>
(where T : Game
), so it is unlikely to cause problems.
If reflection is involved at all, I'd use the second form, perhaps offering both:
void Foo<T>() where T : Game
{
Foo(typeof(T));
}
void Foo(Type type) {...}
Most generic features can be emulated - for example Activator.CreateInstance(type)
in place of new T()
- or a cast to a known interface in place of T : ISomeInterface
. You don't get the use of the "constrained" opcode, but in your case that doesn't apply anyway.
精彩评论