Dynamically create generic C# object using reflection | 动态创建C#泛型实例

Classes referenced by generic type:

public class Cat
{
    ...
}
public class Dog
{
    ...
}

Generic class:

public class Animals<T>
{
    public Animals(int id, T body)
    {
        Id = id;
        Body = body;
    }

    public int Id { get; set; }

    public T Body { get; set; }
}

Create instance for generic class dynamically:

using System;
using Newtonsoft.Json;

namespace RtxService.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
                var cat = new Cat()
                {
                    ...
                };

                var type = typeof(Cat);
                var genericType = typeof(Animals<>).MakeGenericType(type);
                var animal = Activator.CreateInstance(
                    genericType,
                    1,
                    JsonConvert.DeserializeObject(cat, type));
        }
    }
}

refs:
https://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection

Leave a Comment