[c#] C # 리플렉션 : 문자열에서 클래스 참조를 얻는 방법은 무엇입니까?

C #에서이 작업을 수행하고 싶지만 방법을 모르겠습니다.

클래스 이름 -eg : 문자열이 있고이 클래스 FooClass에서 (정적) 메서드를 호출하고 싶습니다.

FooClass.MyMethod();

분명히 리플렉션을 통해 클래스에 대한 참조를 찾아야하지만 어떻게해야합니까?



답변

Type.GetType방법 을 사용하고 싶을 것 입니다.

다음은 매우 간단한 예입니다.

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

이렇게 하면 동일한 어셈블리 내부에있는 유형을 찾기가 매우 쉽기 때문에 간단 하다고 말합니다 . 그것에 대해 알아야 할 사항에 대한 자세한 설명 은 Jon의 답변 을 참조하십시오 . 유형을 검색하면 내 예제는 메소드를 호출하는 방법을 보여줍니다.


답변

을 사용할 수 Type.GetType(string)있지만 네임 스페이스를 포함한 전체 클래스 이름 을 알아야 하며 현재 어셈블리 또는 mscorlib에없는 경우 어셈블리 이름이 대신 필요합니다. (이상적으로는 Assembly.GetType(typeName)대신 사용하십시오-어셈블리 참조를 올바르게 얻는 측면에서 더 쉽습니다!)

예를 들면 :

// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");

// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");

// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " +
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " +
    "PublicKeyToken=b77a5c561934e089");


답변

간단한 사용 :

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

견본:

Type dogClass = Type.GetType("Animals.Dog, Animals");


답변

답장에 조금 늦었지만 이것이 트릭을 할 것입니다.

Type myType = Type.GetType("AssemblyQualifiedName");

어셈블리 정규화 된 이름은 다음과 같아야합니다.

"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"


답변

Type.GetType 을 통해 유형 정보를 얻을 수 있습니다. 이 클래스를 사용 하여 메서드 정보를 가져온 다음 메서드 를 호출 할 수 있습니다 (정적 메서드의 경우 첫 번째 매개 변수를 null로 유지).

유형을 올바르게 식별하기 위해 어셈블리 이름 이 필요할 수도 있습니다 .

형식이 현재 실행중인 어셈블리 또는 Mscorlib.dll에있는 경우 해당 네임 스페이스로 한정된 형식 이름을 제공하는 것으로 충분합니다.


답변

우리는 사용할 수 있습니다

Type.GetType ()

클래스 이름을 가져오고 사용하여 객체를 만들 수도 있습니다. Activator.CreateInstance(type);

using System;
using System.Reflection;

namespace MyApplication
{
    class Application
    {
        static void Main()
        {
            Type type = Type.GetType("MyApplication.Action");
            if (type == null)
            {
                throw new Exception("Type not found.");
            }
            var instance = Activator.CreateInstance(type);
            //or
            var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
        }
    }

    public class Action
    {
        public string key { get; set; }
        public string Value { get; set; }
    }
}


답변