CommandBase 클래스에서 상속하는 여러 클래스가 포함 된 dll이 있습니다. C#에서 리플렉션을 사용하여 이러한 모든 클래스 (CommandA, CommandB, CommandC 등)의 인스턴스를 가져 오려고합니다. 각 인스턴스에서 특정 메서드를 호출 할 수 있습니다. 여기에 내가 지금까지 가지고있는 것이있다 :리플렉션을 사용하여 dll의 특정 기본 유형의 모든 클래스 가져 오기
//get assemblies in directory.
string folder = Path.Combine(HttpContext.Current.Server.MapPath("~/"), "bin");
var files = Directory.GetFiles(folder, "*.dll");
//load each assembly.
foreach (string file in files)
{
var assembly = Assembly.LoadFile(file);
if (assembly.FullName == "MyCommandProject")
{
foreach (var type in assembly.GetTypes())
{
if (!type.IsClass || type.IsNotPublic) continue;
if(type is CommandBase)
{
var command = Activator.CreateInstance(type) as CommandBase;
}
}
}
}
나는 2 개의 이슈를 가지고있다. 첫 번째 문제는 "if (type is CommandBase") 줄에 다음 경고가 표시된다는 것입니다.
제공된 표현식은 CommandBase 유형으로 제공되지 않습니다.
두 번째 문제는 실제 객체 (CommandA, CommandB 등 ...)의 인스턴스를 얻는 방법을 알아 내지 못하고 CommandBase로 변환하는 것으로 충분하지 않다는 것입니다.
마지막 행에서 인스턴스가 제대로 생성되지 않습니까? 'Activator.CreateInstance()'를 사용하면 CommandA, CommandB ... class ('type'에 따라) 인스턴스가 있어야합니다. –
Activation.CreateInstance()는 type 객체를 반환합니다. – Justin
예. 제공 한 유형의 오브젝트를 리턴합니다. 당신은 "object"var 또는 "CommandBase"var에 저장할 수 있습니다. 여전히 CommandA, CommandB 등의 인스턴스가됩니다. 나중에 "진짜"유형으로 캐스팅 할 수 있습니다. 확인할 Visual Studio가 없지만 문제가 무엇인지 모르겠습니다. –