문제

문자열을 .NET의 유형 객체로 변환하는 가장 좋은 방법은 무엇입니까?

고려해야 할 문제 :

  • 유형은 다른 어셈블리에있을 수 있습니다.
  • 유형의 어셈블리는 아직로드되지 않을 수 있습니다.

이것은 내 시도이지만 두 번째 문제는 다루지 않습니다.

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
도움이 되었습니까?

해결책

두 번째로 getReferenceSemblies () 메소드를 호출해야 할 수도 있습니다.

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 (문자열) 이것을하기 위해. 유형 이름은 어셈블리 자격을 갖추어야하지만 방법은 필요에 따라 어셈블리를로드합니다. 유형이 mscorlid 또는 gettype 호출을 실행하는 어셈블리에있는 경우 어셈블리 자격이 필요하지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top