2010-03-27 4 views
4

. NET 응용 프로그램 (C#)에서 런타임에 클래스가 정의되어 있는지를 조건부로 감지 할 수 있습니까?.NET에서 런타임에 클래스의 존재를 감지하는 방법은 무엇입니까?

구현 예 - 구성 옵션을 기반으로 클래스 개체를 만들겠습니까? 당신이 클래스를 인스턴스화 할 수없는 경우

물론 http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

, 그것은 예외가 발생, 같은 일이 있는지 정확히되지 않습니다 :

+0

Type.GetType ("someType")의 문제점은 무엇입니까? –

답변

2

I've done something like that, 구성에서 클래스를로드하고 인스턴스화하십시오. 이 예제에서는 config에서 지정된 클래스가 NinjectModule이라는 클래스에서 상속되었는지 확인해야했지만 아이디어를 얻은 것으로 보입니다.

protected override IKernel CreateKernel() 
{ 
    // The name of the class, e.g. retrieved from a config 
    string moduleName = "MyApp.MyAppTestNinjectModule"; 

    // Type.GetType takes a string and tries to find a Type with 
    // the *fully qualified name* - which includes the Namespace 
    // and possibly also the Assembly if it's in another assembly 
    Type moduleType = Type.GetType(moduleName); 

    // If Type.GetType can't find the type, it returns Null 
    NinjectModule module; 
    if (moduleType != null) 
    { 
     // Activator.CreateInstance calls the parameterless constructor 
     // of the given Type to create an instace. As this returns object 
     // you need to cast it to the desired type, NinjectModule 
     module = Activator.CreateInstance(moduleType) as NinjectModule; 
    } 
    else 
    { 
     // If the Type was not found, you need to handle that. You could instead 
     // initialize Module through some default type, for example 
     // module = new MyAppDefaultNinjectModule(); 
     // or error out - whatever suits your needs 
     throw new MyAppConfigException(
      string.Format("Could not find Type: '{0}'", moduleName), 
      "injectModule"); 
    } 

    // As module is an instance of a NinjectModule (or derived) class, we 
    // can use it to create Ninject's StandardKernel 
    return new StandardKernel(module); 
} 
0

Activator.CreateInstance로 법안에 맞게 수 클래스 "존재". 그러나 인스턴스화 할 수없고 정적 멤버를 호출하지 않으려는 경우에는 속임수를 수행해야합니다.

문자열 매개 변수가있는 오버로드를 찾고 있습니다. 첫 번째 인수는 어셈블리의 이름이어야하며 두 번째 인수는 클래스의 이름 (완전히 네임 스페이스 한정)이어야합니다. 질문의 두 번째 부분에 대한

+0

MSDN에 따르면 Actiator.CreateInstance()는 "값 비싼 함수"중 하나입니다 (http://msdn.microsoft.com/en-us/magazine/cc163759.aspx). 또한 예외를 throw하는 것이 비용이 많이 드는 이유는 무엇입니까? –

+1

"Costly"는 상대적입니다. 당신이 공동으로이 일을 몇 번한다면, 그렇게 비싸지는 않습니다. 수백만 번 반복한다면 더 나은 솔루션을 찾고 싶을 것입니다. – Gabe

3
string className="SomeClass"; 
Type type=Type.GetType(className); 
if(type!=null) 
{ 
//class with the given name exists 
} 

: -

샘플 구현 - 당신이 이 구성 옵션에 따라 클래스 객체를 생성하고 싶은 말은?

왜 그런지 알고 싶지 않습니다. 그러나 클래스가 인터페이스를 구현하고 구성 파일을 기반으로 해당 클래스의 객체를 동적으로 만들려는 경우 Unity IoC 컨테이너을 볼 수 있다고 생각합니다. 그게 정말 멋지고 사용하기가 매우 쉽습니다. 이를 수행하는 방법의 예는 here입니다.

+0

@Ashish : 구성에서 인스턴스를 생성하는 것은 Unity가하는 일 중 하나입니다. –

+0

@ John. 나는 그것이 주로 의존성 주입에 사용된다는 것을 알고있다. 나는 그가 방금 그것을 보았을 것을 제안하고 있었다. 질문에 대한 대답이 아닐 수도 있습니다. 어쨌든 고마워. –

관련 문제