简体   繁体   English

C#如何在代码中动态实例化类型

[英]C# How to instantiate type dynamically in code

I would like to know if there is a way to instantiate a generic T type into a true type but dynamically, on execution time.我想知道是否有办法将泛型 T 类型实例化为真正的类型,但在执行时是动态的。

Here is an example of code:这是一个代码示例:

public enum InventoryType
{
    Car,
    Dog,
    House
    Cat
}

public static class Main{

    private readonly IApiClient _apiClient;
    private readonly IPostgreSQL _postgreSql;

    public Main()
    {
        foreach (var inventoryType in default(InventoryType).ToEnumerable())
        {
            Type type;
            switch (inventoryType)
            {
                case Car:
                    type = typeof(Car);
                    break;
                case Dog:
                    type = typeof(Dog);
                    break;
                case House:
                    type = typeof(House);
                    break;
                case Cat:
                    type = typeof(Cat);
                    break;
                default:
            }

            var listOfJson = _apiClient.GetRawData(inventoryType);
            List<type> data = JsonConvert.DeserializeObject<List<type>>(listOfJson);
            _postgreSql.StoreData<type>(data);
        }
    }
}

How can I convert generic T type as true class object and use it as generic T type?如何将泛型 T 类型转换为真正的类对象并将其用作泛型 T 类型? For understand: how can I write _postgreSql.StoreData<Car>(data) instead of _postgreSql.StoreData<T>(data) where Car is an variable ?为了理解:我怎样才能写_postgreSql.StoreData<Car>(data)而不是_postgreSql.StoreData<T>(data)其中Car是一个变量?

the easiest way would be something like this最简单的方法是这样的

public Main()
{
    foreach (var inventoryType in default(InventoryType).ToEnumerable())
    {
        switch (inventoryType)
        {
            case Car:
                SaveData<Car>(inventoryType);
                break;
            case Dog:
                SaveData<Dog>(inventoryType);
                break;
            case House:
                SaveData<House>(inventoryType);
                break;
            case Cat:
                SaveData<Cat>(inventoryType);
                break;
            default:
        }
    }
}

private static void SaveData<T>(InventoryType inventoryType)
{
    var listOfJson = _apiClient.GetRawData(inventoryType);
    var data = JsonConvert.DeserializeObject<List<T>>(listOfJson);
    _postgreSql.StoreData(data);
    
}

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

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