Dynamically create an object of

前端 未结 6 1431
时光说笑
时光说笑 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:18
    public static T GetInstance<T>(params object[] args)
    {
         return (T)Activator.CreateInstance(typeof(T), args);
    }
    

    I would use Activator.CreateInstance() instead of casting, as the Activator has a constructor for generics.

    0 讨论(0)
  • 2020-12-02 17:19

    Here is a function I wrote that clones a record of type T, using reflection. This is a very simple implementation, I did not handle complex types etc.

     public static T Clone<T>(T original)
        {
            T newObject = (T)Activator.CreateInstance(original.GetType());
    
            foreach (var prop in original.GetType().GetProperties())
            {
                prop.SetValue(newObject, prop.GetValue(original));
            }
    
            return newObject;
        }
    

    I hope this can help someone.

    Assaf

    0 讨论(0)
  • 2020-12-02 17:20

    You want to use Activator.CreateInstance.

    Here is an example of how it works:

    using System;
    using System.Runtime.Remoting;
    
    class Program
    {
        static void Main()
        {
            ObjectHandle o = Activator.CreateInstance("mscorlib.dll", "System.Int32");
    
            Int32 i = (Int32)o.Unwrap();
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:26

    This link should help:
    https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

    Activator.CreateInstance will create an instance of the specified type.

    You could wrap that in a generic method like this:

    public T GetInstance<T>(string type)
    {
        return (T)Activator.CreateInstance(Type.GetType(type));
    }
    
    0 讨论(0)
  • 2020-12-02 17:27

    Assuming you have the following type:

    public class Counter<T>
    {
      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<int> counter = 
      (Counter<int>)Activator.CreateInstance(
        t.MakeGenericType(typeof(int)));
    
    counter.Value++;
    Console.WriteLine(counter.Value);
    
    0 讨论(0)
  • 2020-12-02 17:29

    If the type is known by the caller, there's a better, faster way than using Activator.CreateInstance: you can instead use a generic constraint on the method that specifies it has a default parameterless constructor.

    Doing it this way is type-safe and doesn't require reflection.

    T CreateType<T>() where T : new()
    {
       return new T();
    }
    
    0 讨论(0)
提交回复
热议问题