简体   繁体   中英

Create a class with Optional Generic Type <T>

Let's say we have a class that looks like this:

public class Repository<T>
{
    private readonly string _connectionString;

    public Repository(string connectionString)
    {
        _connectionString = connectionString;
    }

    void T SomeMethod()
    {
       // do work here
       return T;
    }
}

In the case above, the Type would need to be declared along with the class, but you would not need to specify the Type when calling SomeMethod() .

Or, you could also do this:

public class Repository
{    
    private readonly string _connectionString;

    public Repository(string connectionString)
    {
        _connectionString = connectionString;
    }

    void T SomeMethod<T>()
    {
       // do work here
       return T;
    }
}

In this case, the class would be created without a Type, but you would need to declare the Type when calling SomeMethod() .

Without a total duplication of all code, how would one create the same class so that the Type was optional when creating it? In other words, I'd like both of these to work upstream:

Repository<MyType> repo = new Repository<MyType>();
var something = repo.SomeMethod();

and

Repository repo = new Repository();
var something = repo.SomeMethod<MyType>();

If this is what you want to achieve, you could minimise duplication by wrapping the generic method implementation:

public class Repository
{
    public T SomeMethod<T>()
    {
        //Impl.
    }
}

public class Repository<T>
{
    private readonly Repository _base;

    public Repository()
    {
        _base = new Repository();
    }

    public T SomeMethod() => _base.SomeMethod<T>();
}

Where the generic class simply proxies through to the generic methods.

EDIT

Same concept as above, passing injected connectionString through to wrapped instance.

public class Repository
{
    private readonly string _connectionString;

    public Repository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public T SomeMethod<T>()
    {
        //Impl.
    }
}

public class Repository<T>
{
    private readonly Repository _base;

    public Repository(string connectionString)
    {
        _base = new Repository(connectionString);
    }

    public T SomeMethod() => _base.SomeMethod<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