简体   繁体   English

创建一个具有可选泛型类型的类<T>

[英]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() .在上述情况下,该类型需要与类一起被声明,但你不会需要时调用指定类型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() .在这种情况下,类将没有类型来创建的,但你需要打电话时申报类型SomeMethod()

Without a total duplication of all code, how would one create the same class so that the Type was optional when creating it?如果没有所有代码的完全重复,如何创建相同的类,以便在创建它时 Type 是可选的? 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.与上面相同的概念,将注入的connectionString传递给包装的实例。

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>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM