Compact Framework: come posso creare dinamicamente un tipo senza costruttore predefinito?

StackOverflow https://stackoverflow.com/questions/29436

Domanda

Sto utilizzando .NET CF 3.5.Il tipo che voglio creare non ha un costruttore predefinito, quindi voglio passare una stringa a un costruttore sovraccaricato.Come faccio a fare questo?

Codice:

Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type

string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException
È stato utile?

Soluzione

MyObj o = null;
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");

ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });
if(ctor != null)
   o = ctor.Invoke(new object[] { s });

Altri suggerimenti

@Jonathan Perché il Compact Framework deve essere il più snello possibile.Se esiste un altro modo per fare qualcosa (come il codice che ho pubblicato), generalmente non duplicano la funzionalità.

Rory Blyth una volta descrisse il Compact Framework come "un wrapper attorno a System.NotImplementedExcetion".:)

Ok, ecco un metodo di supporto originale per darti un modo flessibile per attivare un tipo dato un array di parametri:

static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) 
{
    var t = a.GetType(typeName);

    var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray());
    if (c == null) return null;

    return c.Invoke(pars);
}

E lo chiami così:

Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo;

Quindi passi l'assembly e il nome del tipo come primi due parametri, quindi tutti i parametri del costruttore in ordine.

Vedi se questo funziona per te (non testato):

Type t = a.GetType("type info here");
var ctors = t.GetConstructors();
string s = "Pass me to the ctor of t";
MyObj o = ctors[0].Invoke(new[] { s }) as MyObj;

Se il tipo ha più di un costruttore, potresti dover fare qualche lavoro di fantasia per trovare quello che accetta il tuo parametro di stringa.

Modificare:Ho appena testato il codice e funziona.

Modifica2: La risposta di Chris mostra il gioco di gambe fantasioso di cui stavo parlando!;-)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top