C # Riflessione, utilizzando MakeGenericMethod con il metodo che ha il 'nuovo) (' tipo di vincolo
-
24-09-2019 - |
Domanda
Sto provando ad usare il MethodInfo MakeGenericMethod come segue:
foreach (var type in types)
{
object output = null;
var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
var genmethod = method.MakeGenericMethod(type);
var arr = new object[] { from, output };
if ((bool)genmethod.Invoke(null, arr))
return (IThingy)arr[1];
}
Contro il seguente metodo generico:
public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
{
var thing = new T();
return thingTryConstructFrom(from, out result);
}
Il problema che avendo è che ottengo un'eccezione arguement sulla linea MakeGenericMethod come tipo sto passando non è 'new ()'
C'è un modo intorno a questo ?? Grazie
Soluzione
No. Si possono effettuare chiuso costruito solo metodi TryConstruct con parametri di tipo che soddisfano i vincoli IThingy
e new
. In caso contrario, si sarebbe sconfiggendo il contratto TryConstruct: cosa sarebbe successo quando hai chiamato TryConstruct ed ha colpito la linea new T()
? Non ci sarebbe essere un costruttore T (), in modo che ci avete violato la sicurezza tipo.
È necessario controllare che tipo ha un costruttore di default pubblico prima di passarlo a MakeGenericMethod. Se avete bisogno di istanziare i tipi con un costruttore non predefinito, è necessario creare un nuovo metodo o un sovraccarico del TryConstruct, forse uno che utilizza Activator.CreateInstance invece di new T()
.