C # Riflessione, utilizzando MakeGenericMethod con il metodo che ha il 'nuovo) (' tipo di vincolo

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

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

È stato utile?

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().

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