7

.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
4

2 に答える 2

10

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

于 2009-03-03T21:41:40.990 に答える
3

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);
        }
    }
}
于 2009-03-03T21:48:09.273 に答える