Dynamically create an object of

前端 未结 6 1435
时光说笑
时光说笑 2020-12-02 16:40

I have a table in my database that I use to manage relationships across my application. it\'s pretty basic in it\'s nature - parentType,parentId, childType, childId... all a

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 17:27

    Assuming you have the following type:

    public class Counter
    {
      public T Value { get; set; }
    }
    

    and have the assembly qualified name of the type, you can construct it in the following manner:

    string typeName = typeof(Counter<>).AssemblyQualifiedName;
    Type t = Type.GetType(typeName);
    
    Counter counter = 
      (Counter)Activator.CreateInstance(
        t.MakeGenericType(typeof(int)));
    
    counter.Value++;
    Console.WriteLine(counter.Value);
    

提交回复
热议问题