質問

.NETで文字列をTypeオブジェクトに変換する最良の方法は何ですか?

考慮すべき問題:

  • 型は別のアセンブリにある可能性があります。
  • 型のアセンブリはまだロードされていない可能性があります。

これは私の試みですが、2番目の問題に対処していません

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
役に立ちましたか?

解決

2番目のGetReferencedAssemblies()メソッドを呼び出す必要がある場合があります。

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);
        }
    }
}

他のヒント

Type.GetType(string)を使用して、これを行う。型名はアセンブリ修飾する必要がありますが、メソッドは必要に応じてアセンブリをロードします。型がmscorlidにある場合、またはGetType呼び出しを実行するアセンブリの場合、アセンブリの資格は必要ありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top