简体   繁体   中英

Creating an instance of generic class, how to easily set the type to the calling class

I have a generic class LoggerHelper<T> . There are properties in many different classes in the application, whose values are to be set to instances of LoggerHelper . In the constructors of these classes, this property will be set. For example:

public class Importer
{
    ILogger _logger;

    public Importer()
    {  
        this._logger = new LoggerHelper<Importer>();
    }
}

How can I avoid specifying the type each time? Is there are suitable pattern for this?

You could use a factory method, thus a type could be inferred by the compiler.


Static method

public static class LoggerHelperFactory
{
    public static LoggerHelper<T> Create<T>(T instance)
    {
        return new LoggerHelper<T>();
    }
}

Then you can call it as:

_logger = LoggerHelperFactory.Create(this);

Extension method

public static class LoggerHelperFactoryExtensions
{
    public static LoggerHelper<T> CreateLogger<T>(this T instance)
    {
        return new LoggerHelper<T>();
    }
}

Usage:

_logger = this.CreateLogger();

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