简体   繁体   中英

How can I pass in a type as a parameter, and use it to declare the type of variables in my function?

I'm fairly new to C# and I ran into a problem I couldn't find a clear answer to.

I have a base class "Entity". This class is extended by several "Entities". Currently, I have a function that knows how to load each different kind of "Entities" from a database. I would like to replace all of these functions with one function that knows how to load the base class "Entity" from the database.

Here is an example of function that knows how to load only one type, the "TestPlan" type.

    public List<TestPlan> LoadTestPlans()
    {
        List<TestPlan> testPlans = new List<TestPlan>();
        using (ITransaction transaction = session.BeginTransaction())
        {
            testPlans = (List<TestPlan>)session.CreateCriteria<TestPlan>().List<TestPlan>();
            transaction.Commit();
        }
        return testPlans;
    }

I would like to replace it with something like this, but I can't figure out the right incantation for the type casting.

    public List<Entity> LoadEntities(Type entityType)
    {

        List<entityType> entities= new List<entityType>();
        using (ITransaction transaction = session.BeginTransaction())
        {
            entities= (List<entityType>)session.CreateCriteria<entityType>().List<entityType>();
            transaction.Commit();
        }
        return entities;
    }

I've seen some things with a generic type List, I'm not sure how that works. I'm a little hesitant to go down the generic type route. I want compile time errors if you try to call the function with the wrong type passed in.

You can use the generic method:

public List<T> LoadEntities<T>() where T: Entity
{

    List<T> entities= new List<T>();
    using (ITransaction transaction = session.BeginTransaction())
    {
        entities= (List<T>)session.CreateCriteria<T>().List<T>();
        transaction.Commit();
    }
    return entities;
}

When you use this code you need to provide the type that you desire instead of 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