2017-12-14 2 views
0

리플렉션을 사용하여 어셈블리에 모든 유형이 있습니다. 내가 그것을 인터페이스 "ICommand의"런타임에서 유형을 명시 적으로 인터페이스에 캐스팅하는 방법

ICommand C; 
foreach(Type t in asm.GetTypes()) 
{ 

    if (t.GetInterfaces()[0].Name is "ICommand") 
    { 
     C = (ICommand)t; //throws Exception here - Unable 
         //to cast to ICommand 
     RootDir.AddCommand(C, t.Namespace.Split('.')); 
    } 
} 

나는이 같은를 구현하는 방법을

public interface ICommand 
{ 
    string HelpDescription { get; } 
    void Execute(CommandClass CC); 
} 


class CurrentDir : ICommand 
{ 
    public string HelpDescription => "Current Directory - Change current directory"; 

    public static explicit operator CurrentDir (Type T) 
    { 
     return new CurrentDir(); 
    } 

    void ICommand.Execute(CommandClass CC) 
    { 
     throw new NotImplementedException(); 
    } 
} 

캐스팅하려고 유형의 예를 구현하는 것을 알고 있다면 어떻게 ICommand의에 유형 t 전송할 수 있습니다 그것은 System.Type에서 ICommand로 변환 할 수 있습니까?

답변

7

t 유형이 Type 인 것을 ICommand으로 전송하려고합니다. 구현하지 않습니다.

var obj = Activator.CreateInstance(t); 
var C = (ICommand)obj; 
: 당신이해야 할 어떤 코드의 모습에서

은 캐스팅 후 t의 인스턴스를 생성하고있다

관련 문제