reflection: Instanc von Type t erzeugen
-
Ich habe einen System.Type t.
1. Wie kann ich eine neue Instanz unter Angabe von Konstruktorparametern erzeugen, also in Pseudocode:
Type t = SomeType(); object a = Something(); object b = new object-of-type-t(a);
2. Kann ich prüfen, daß t instanzierbar ist und einen entsprechenden Konstrucktor besitzt, ohne eine Instanz zu erzeugen?
-
Zu Nummer 1:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { object inst = System.Reflection.Assembly.GetEntryAssembly().CreateInstance( typeof(foo).FullName, true, System.Reflection.BindingFlags.CreateInstance, null, new object[] { 10 }, CultureInfo.CurrentCulture, null); Console.WriteLine((inst as foo).Value); } } public class foo { int x = 0; public foo(int value) { Value = value; } public int Value { get { return x; } private set { x = value; } } } }
Nummer 2:
static void Main(string[] args) { bool ctorexists = typeof(foo).FindMembers(MemberTypes.Constructor, BindingFlags.Public | BindingFlags.Instance, new MemberFilter( filter ), new object[] { typeof( int ) } ).Length > 0; if ( ctorexists ) Console.WriteLine("ctor existiert"); Console.ReadKey(); } static bool filter (MemberInfo m, object filter) { int i = 0; bool result = m.MemberType == MemberTypes.Constructor; if (filter == null || !filter.GetType().IsArray) throw new ArgumentException("Keine parameter angegeben", "filter"); if ( result ) { Array.ForEach((m as ConstructorInfo).GetParameters(), delegate(ParameterInfo info) { try { if (!info.ParameterType.Equals(((object[])filter)[i++])) { result = false; return; } } catch { result = false; } }); } return result; }
Naja... Vom Prinzip her zeigt es die theoretische Vorgehensweise!
-
Zu 1.: Das geht auch einfacher, über 'Activator.CreateInstance<T>'.
-
Konrad Rudolph schrieb:
Zu 1.: Das geht auch einfacher, über 'Activator.CreateInstance<T>'.
Ja, stimmt!
-
Dankeschön erstmal! Leider ist mir mein MoBo oder schlimmeres abgeraucht, werd's sofort ausprobieren (und auseinandernehmen), wenn ich wieder lauffähig bin.