Reputation: 2492
I have generic method:
private ILogger _logger; //get logger something else.
public T GetService<T>(ServiceType type)
{
//how to return _logger?
}
How can i return T? For example, i have ILogger:
var logger=GetService<ILogger>(log);
How to implement GetService method? Thank you!
P.S. yes, i try to get one and more types from GetService method. For example: Logger, some other infrastructure classes. I know, that ServiceLocator is not right choise (is it uses in many places),but in my way (GetService will be use in one place: to get infrastructure for my plugins) i hope it is normal.
Upvotes: 5
Views: 29492
Reputation: 1967
You have to declare T
as new()
, so it has to have a parameterless constructor. Then you can simply create an instance and return it:
public T GetService<T>(ServiceType type) where T : new()
{
T t = new T();
return t;
}
Now, instead of new T()
you could use others, may be your ServiceType
..
Upvotes: -5
Reputation: 117037
It sounds like you are trying to create some sort of factory method based on type. Perhaps this might help:
public class Factory
{
private ILogger _logger; //get logger something else.
public Factory()
{
_factories = new Dictionary<Type, Func<Type, object>>()
{
{ typeof(ILogger), t => _logger },
};
}
private Dictionary<Type, Func<Type, object>> _factories;
public T GetService<T>()
{
var t = typeof(T);
return (T)_factories[t].Invoke(t);
}
}
Upvotes: 6
Reputation: 419
try this:
private ILogger _logger; //get logger something else.
public T GetService<T>(ServiceType type)
{
// codes here...
return (T)(object) _logger;
}
Upvotes: 6
Reputation: 156948
I would start to make sure T
implements ILogger
. Then you have to cast the instance to T
:
public T GetService<T>(ServiceType type) where T : ILogger
{
return (T)_logger;
}
Note that this can cause invalid casts. To prevent exceptions on this and instead return null, you can use as
:
public T GetService<T>(ServiceType type) where T : ILogger
{
return _logger as T;
}
Upvotes: 1