C # Can I create a generic method or property inside a non-generic class that returns another generic class?

I have an abstract generic class. I want to define a method internally, so I don’t have to do this in all derived classes.

Basically I need to get a repository class based on the type that will have a common class.

I am returning repoistories through another class that is not generic.

How can I let this class return a common repository based on the type that the common caller has?

I was hoping for something like this.

public IRepository<T> Table<T>()
{
    return _container.Resolve<IRepository<T>>();
}

If it is a property, it will be even better.

+3
source share
2 answers

. , . , ?

interface IRepository<T>
{
    T GetData();
}

class Container
{
    private object[] data = null;

    public T Resolve<T>()
    {
        return(T)data.First(t => t.GetType() is T);
    }
}

abstract class Handler<T>
{
    private Container _container;

    public IRepository<T> Table
    {
        get
        {
            return _container.Resolve<IRepository<T>>();
        }
    }
}
+1

# "self", (CRTP).

public class Base<TSelf> where TSelf : Base<TSelf> 
{
    // Make this a property if you want.
    public IRepository<TSelf> GetTable()
    {                   
        return _container.Resolve<IRepository<TSelf>>();          
    }
}

public class Derived : Base<Derived> {  }

:

IRepository<Derived> table = new Derived().GetTable();  

, , . : .


, _container.Resolve, , , . :

// If the container Resolve method had an overload that 
// accepted a System.Type, it would be even easier.
public SomeBaseType GetTable()
{
   var repositoryType = typeof(IRepository<>).MakeGenericType(GetType());

   var result = _container.GetType()
                          .GetMethod("Resolve")
                          .MakeGenericMethod(repositoryType)
                          .Invoke(_container, null);

   return (SomeBaseType) result;     
}
+6

Source: https://habr.com/ru/post/1793611/


All Articles