Cum de a crea un obiect nou exemplu de la un Tip

Nimeni nu poate ști întotdeauna " Tip "de un obiect la compilare, dar ar putea avea nevoie pentru a crea un exemplu de "Tip". Cum puteți obține un obiect nou exemplu de la un "Tip"?

Soluția

Anii `Activator clasa în rădăcina "Sistem" spațiu de nume este destul de puternic.

Există o mulțime de suprasarcini pentru transmiterea parametrilor către constructor și astfel. A verifica afară de documentația la:

sau (drum nou)

Aici sunt câteva exemple simple:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
Comentarii (6)
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

Anii `Activator clasa are un generic varianta care face acest lucru un pic mai ușor:

ObjectType instance = Activator.CreateInstance();
Comentarii (6)

Compilate de exprimare este cel mai bun mod! (pentru performanță să creați în mod repetat instanță în execuție).

static readonly Func YCreator = Expression.Lambda(
   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
 ).Compile();

X x = YCreator();

Statistică (2012):

    Iterations: 5000000
    00:00:00.8481762, Activator.CreateInstance(string, string)
    00:00:00.8416930, Activator.CreateInstance(type)
    00:00:06.6236752, ConstructorInfo.Invoke
    00:00:00.1776255, Compiled expression
    00:00:00.0462197, new

Statistică (2015, .net 4.5, x64):

    Iterations: 5000000
    00:00:00.2659981, Activator.CreateInstance(string, string)
    00:00:00.2603770, Activator.CreateInstance(type)
    00:00:00.7478936, ConstructorInfo.Invoke
    00:00:00.0700757, Compiled expression
    00:00:00.0286710, new

Statistică (2015, .net 4.5, x86):

    Iterations: 5000000
    00:00:00.3541501, Activator.CreateInstance(string, string)
    00:00:00.3686861, Activator.CreateInstance(type)
    00:00:00.9492354, ConstructorInfo.Invoke
    00:00:00.0719072, Compiled expression
    00:00:00.0229387, new

Statistică (2017, LINQPad 5.22.02/x64/.NET 4.6):

    Iterations: 5000000
    No args
    00:00:00.3897563, Activator.CreateInstance(string assemblyName, string typeName)
    00:00:00.3500748, Activator.CreateInstance(Type type)
    00:00:01.0100714, ConstructorInfo.Invoke
    00:00:00.1375767, Compiled expression
    00:00:00.1337920, Compiled expression (type)
    00:00:00.0593664, new
    Single arg
    00:00:03.9300630, Activator.CreateInstance(Type type)
    00:00:01.3881770, ConstructorInfo.Invoke
    00:00:00.1425534, Compiled expression
    00:00:00.0717409, new

Statistică (2019, x64/.NET 4.8):

Iterations: 5000000
No args
00:00:00.3287835, Activator.CreateInstance(string assemblyName, string typeName)
00:00:00.3122015, Activator.CreateInstance(Type type)
00:00:00.8035712, ConstructorInfo.Invoke
00:00:00.0692854, Compiled expression
00:00:00.0662223, Compiled expression (type)
00:00:00.0337862, new
Single arg
00:00:03.8081959, Activator.CreateInstance(Type type)
00:00:01.2507642, ConstructorInfo.Invoke
00:00:00.0671756, Compiled expression
00:00:00.0301489, new

Statistică (2019, x64/.NET Core 3.0):

Iterations: 5000000
No args
00:00:00.3226895, Activator.CreateInstance(string assemblyName, string typeName)
00:00:00.2786803, Activator.CreateInstance(Type type)
00:00:00.6183554, ConstructorInfo.Invoke
00:00:00.0483217, Compiled expression
00:00:00.0485119, Compiled expression (type)
00:00:00.0434534, new
Single arg
00:00:03.4389401, Activator.CreateInstance(Type type)
00:00:01.0803609, ConstructorInfo.Invoke
00:00:00.0554756, Compiled expression
00:00:00.0462232, new

Cod complet:

static X CreateY_New()
{
    return new Y();
}

static X CreateY_New_Arg(int z)
{
    return new Y(z);
}

static X CreateY_CreateInstance()
{
    return (X)Activator.CreateInstance(typeof(Y));
}

static X CreateY_CreateInstance_String()
{
    return (X)Activator.CreateInstance("Program", "Y").Unwrap();
}

static X CreateY_CreateInstance_Arg(int z)
{
    return (X)Activator.CreateInstance(typeof(Y), new object[] { z, });
}

private static readonly System.Reflection.ConstructorInfo YConstructor =
    typeof(Y).GetConstructor(Type.EmptyTypes);
private static readonly object[] Empty = new object[] { };
static X CreateY_Invoke()
{
    return (X)YConstructor.Invoke(Empty);
}

private static readonly System.Reflection.ConstructorInfo YConstructor_Arg =
    typeof(Y).GetConstructor(new[] { typeof(int), });
static X CreateY_Invoke_Arg(int z)
{
    return (X)YConstructor_Arg.Invoke(new object[] { z, });
}

private static readonly Func YCreator = Expression.Lambda(
   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
).Compile();
static X CreateY_CompiledExpression()
{
    return YCreator();
}

private static readonly Func YCreator_Type = Expression.Lambda(
   Expression.New(typeof(Y))
).Compile();
static X CreateY_CompiledExpression_Type()
{
    return YCreator_Type();
}

private static readonly ParameterExpression YCreator_Arg_Param = Expression.Parameter(typeof(int), "z");
private static readonly Func YCreator_Arg = Expression.Lambda(
   Expression.New(typeof(Y).GetConstructor(new[] { typeof(int), }), new[] { YCreator_Arg_Param, }),
   YCreator_Arg_Param
).Compile();
static X CreateY_CompiledExpression_Arg(int z)
{
    return YCreator_Arg(z);
}

static void Main(string[] args)
{
    const int iterations = 5000000;

    Console.WriteLine("Iterations: {0}", iterations);

    Console.WriteLine("No args");
    foreach (var creatorInfo in new[]
    {
        new {Name = "Activator.CreateInstance(string assemblyName, string typeName)", Creator = (Func)CreateY_CreateInstance},
        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func)CreateY_CreateInstance},
        new {Name = "ConstructorInfo.Invoke", Creator = (Func)CreateY_Invoke},
        new {Name = "Compiled expression", Creator = (Func)CreateY_CompiledExpression},
        new {Name = "Compiled expression (type)", Creator = (Func)CreateY_CompiledExpression_Type},
        new {Name = "new", Creator = (Func)CreateY_New},
    })
    {
        var creator = creatorInfo.Creator;

        var sum = 0;
        for (var i = 0; i < 1000; i++)
            sum += creator().Z;

        var stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < iterations; ++i)
        {
            var x = creator();
            sum += x.Z;
        }
        stopwatch.Stop();
        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);
    }

    Console.WriteLine("Single arg");
    foreach (var creatorInfo in new[]
    {
        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func)CreateY_CreateInstance_Arg},
        new {Name = "ConstructorInfo.Invoke", Creator = (Func)CreateY_Invoke_Arg},
        new {Name = "Compiled expression", Creator = (Func)CreateY_CompiledExpression_Arg},
        new {Name = "new", Creator = (Func)CreateY_New_Arg},
    })
    {
        var creator = creatorInfo.Creator;

        var sum = 0;
        for (var i = 0; i < 1000; i++)
            sum += creator(i).Z;

        var stopwatch = new Stopwatch();
        stopwatch.Start();
        for (var i = 0; i < iterations; ++i)
        {
            var x = creator(i);
            sum += x.Z;
        }
        stopwatch.Stop();
        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);
    }
}

public class X
{
  public X() { }
  public X(int z) { this.Z = z; }
  public int Z;
}

public class Y : X
{
    public Y() {}
    public Y(int z) : base(z) {}
}
Comentarii (6)

O implementare a acestei probleme este de a încerca pentru a apela parametru-mai puțin constructor de Tip:

public static object GetNewObject(Type t)
{
    try
    {
        return t.GetConstructor(new Type[] { }).Invoke(new object[] { });
    }
    catch
    {
        return null;
    }
}

Aici este aceeași abordare, conținute într-o metodă generică:

public static T GetNewObject()
{
    try
    {
        return (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });
    }
    catch
    {
        return default(T);
    }
}
Comentarii (1)

Ei destul de simplu. Presupunem că classname este "Auto" și spațiul de nume este "Vehicule", apoi trece parametru ca `Vehicule.Mașina care returnează obiectul de tip "Auto". Astfel puteți crea orice instanță de orice clasă dinamic.

public object GetInstance(string strNamesapace)
{         
     Type t = Type.GetType(strNamesapace); 
     return  Activator.CreateInstance(t);         
}

Dacă Complet Calificat Nume(de exemplu, Vehiculele.Carîn acest caz) este într-o altă adunare,Tip.GetType` va fi nul. În astfel de cazuri, trebuie bucla prin toate adunările și pentru a găsi "Tip". Pentru asta puteți folosi codul de mai jos

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Și puteți obține de exemplu prin apelarea la metoda de mai sus.

object objClassInstance = GetInstance("Vehicles.Car");
Comentarii (2)

Dacă acest lucru este ceva care va fi numit o mulțime într-o aplicație exemplu,'s mult mai repede pentru a compila și dinamic cache de cod în loc de a folosi activator sau ConstructorInfo.Invoke(). Două opțiuni ușor pentru compilarea dinamică sunt compilate Linq Expresii sau ceva simplu IL opcodes și DynamicMethod. Oricum, diferența este foarte mare atunci când începi să intri în bucle strânse sau mai multe apeluri.

Comentarii (1)

Dacă doriți să utilizați constructorul implicit atunci soluția folosind Sistemul.Activatorprezentate anterior este, probabil, cel mai convenabil. Cu toate acestea, în cazul în care tipul nu are un constructor implicit sau trebuie să utilizați un non-default una, apoi o opțiune este de a utiliza reflecție sau Sistem.ComponentModel.TypeDescriptor. În caz de reflecție, este suficient să știi doar nume de tip (cu nume).

De exemplu, folosind reflecție:

ObjectType instance = 
    (ObjectType)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(
        typeName: objectType.FulName, // string including namespace of the type
        ignoreCase: false,
        bindingAttr: BindingFlags.Default,
        binder: null,  // use default binder
        args: new object[] { args, to, constructor },
        culture: null, // use CultureInfo from current thread
        activationAttributes: null
    );

Exemplu, folosind TypeDescriptor:

ObjectType instance = 
    (ObjectType)System.ComponentModel.TypeDescriptor.CreateInstance(
        provider: null, // use standard type description provider, which uses reflection
        objectType: objectType,
        argTypes: new Type[] { types, of, args },
        args: new object[] { args, to, constructor }
    );
Comentarii (1)

Nu't generic `T t = new T (); munca?

Comentarii (2)

Fără utilizarea de Reflecție:

private T Create() where T : class, new()
{
    return new T();
}
Comentarii (7)

Având în vedere această problemă Activator va funcționa atunci când există o parameterless ctor. Dacă aceasta este o constrângere ia în considerare utilizarea

System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()
Comentarii (0)
public AbstractType New
{
    get
    {
        return (AbstractType) Activator.CreateInstance(GetType());
    }
}
Comentarii (0)

Eu poate peste această întrebare pentru că am fost în căutarea de a pune în aplicare un simplu CloneObject metodă pentru arbitrară de clasă (cu un constructor implicit)

Cu metodă generică puteți solicita ca tipul implementează Noi().

Public Function CloneObject(Of T As New)(ByVal src As T) As T
    Dim result As T = Nothing
    Dim cloneable = TryCast(src, ICloneable)
    If cloneable IsNot Nothing Then
        result = cloneable.Clone()
    Else
        result = New T
        CopySimpleProperties(src, result, Nothing, "clone")
    End If
    Return result
End Function

Cu non-generice-și asume tip are un constructor implicit și prinde o excepție în cazul în care nu't.

Public Function CloneObject(ByVal src As Object) As Object
    Dim result As Object = Nothing
    Dim cloneable As ICloneable
    Try
        cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = Activator.CreateInstance(src.GetType())
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
    Catch ex As Exception
        Trace.WriteLine("!!! CloneObject(): " & ex.Message)
    End Try
    Return result
End Function
Comentarii (0)