简体   繁体   English

如何传递类型作为参数,并使用它在函数中声明变量的类型?

[英]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. 我对C#相当陌生,遇到一个我找不到明确答案的问题。

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. 我想用一个知道如何从数据库中加载基类“ Entity”的函数替换所有这些函数。

Here is an example of function that knows how to load only one type, the "TestPlan" type. 这是一个函数示例,该函数知道如何仅加载一种类型的“ TestPlan”类型。

    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. 我已经看到了一些具有通用类型List的东西,但不确定如何工作。 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 . 使用此代码时,您需要提供所需的类型,而不是T

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

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