Programing

문자열에서 클래스의 인스턴스를 만듭니다.

lottogame 2020. 5. 11. 07:57
반응형

문자열에서 클래스의 인스턴스를 만듭니다.


런타임에 클래스 이름을 알고 있다는 사실을 기반으로 클래스 인스턴스를 만드는 방법이 있습니까? 기본적으로 나는 클래스의 이름을 문자열로 가질 것입니다.


Activator.CreateInstance 메소드를 살펴보십시오 .


꽤 간단합니다. 당신의 클래스 명이라고 가정 Car및 네임 스페이스가되어 Vehicles, 다음과 같이 매개 변수를 전달할 Vehicles.Car반환 타입의 객체 어느 Car. 이와 같이 모든 클래스의 인스턴스를 동적으로 만들 수 있습니다.

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}

귀하의 경우 정규화 된 이름 (즉, Vehicles.Car이 경우) 조립 서로에의는 Type.GetTypenull가됩니다. 이러한 경우 모든 어셈블리를 반복하고를 찾습니다 Type. 이를 위해 아래 코드를 사용할 수 있습니다

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

이제 매개 변수화 된 생성자 를 호출 하려면 다음을 수행하십시오.

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

대신에

Activator.CreateInstance(t);

이 방법을 성공적으로 사용했습니다.

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

반환 된 객체를 원하는 객체 유형으로 캐스트해야합니다.


아마도 내 질문은 더 구체적이었을 것입니다. 실제로 문자열의 기본 클래스를 알고 있으므로 다음과 같이 해결했습니다.

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

Activator.CreateInstance 클래스에는 여러 가지 방법으로 동일한 것을 달성하기위한 다양한 메소드가 있습니다. 나는 그것을 물건에 던질 수 있었지만 위의 상황은 내 상황에 가장 많이 사용됩니다.


나는 게임에 늦었다는 것을 알고 있지만 ... 당신이 찾고있는 해결책은 위의 조합이며 인터페이스를 사용하여 공개적으로 액세스 가능한 측면을 정의하는 것일 수 있습니다.

그런 다음이 방법으로 생성되는 모든 클래스가 해당 인터페이스를 구현하면 인터페이스 유형으로 캐스트하고 결과 객체로 작업 할 수 있습니다.


예를 들어, 데이터베이스 필드 (문자열로 저장 됨)에 다양한 유형의 값을 저장하고 유형 이름 (예 : String, bool, int, MyClass)을 가진 다른 필드가있는 경우 해당 필드 데이터에서 다음을 수행 할 수 있습니다. 위의 코드를 사용하여 모든 유형의 클래스를 작성하고 첫 번째 필드의 값으로 채우십시오. 이것은 물론 문자열을 올바른 유형으로 구문 분석하는 방법을 사용하여 저장하는 유형에 따라 다릅니다. 나는 이것을 데이터베이스에 사용자 환경 설정을 저장하기 위해 여러 번 사용했습니다.


솔루션의 다른 프로젝트에서 클래스 인스턴스를 작성하려면 클래스 이름 (예 : BaseEntity)으로 표시된 어셈블리를 가져 와서 새 인스턴스를 작성할 수 있습니다.

  var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.

ReportClass report = new ReportClass();

The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass)); is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.

I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass available.

참고URL : https://stackoverflow.com/questions/223952/create-an-instance-of-a-class-from-a-string

반응형