Domanda

Qual è il modo migliore per convertire una stringa in un oggetto Type in .NET?

Problemi da considerare:

  • Il tipo potrebbe trovarsi in un assembly diverso.
  • L'assembly del tipo potrebbe non essere ancora caricato.

Questo è il mio tentativo, ma non affronta il secondo problema

Public Function FindType(ByVal name As String) As Type
    Dim base As Type

    base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True)
    If base IsNot Nothing Then Return base

    base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True)
    If base IsNot Nothing Then Return base

    For Each assembly As Reflection.Assembly In _
      AppDomain.CurrentDomain.GetAssemblies
        base = assembly.GetType(name, False, True)
        If base IsNot Nothing Then Return base
    Next
    Return Nothing
End Function
È stato utile?

Soluzione

potresti dover chiamare il metodo GetReferencedAssemblies () per il secondo.

namespace reflectme
{
    using System;
    public class hello
    {
        public hello()
        {
            Console.WriteLine("hello");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
            t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        }
    }
}

Altri suggerimenti

Puoi usare Type.GetType (string) per Fai questo. Il nome del tipo deve essere qualificato come assembly ma il metodo caricherà l'assembly come necessario. La qualifica dell'assembly non è necessaria se il tipo è in mscorlid o l'assembly che esegue la chiamata GetType.

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