2011-08-21 5 views
2

이것은 내가 생각해 낸 것입니다.하지만 이것은 부풀어 오르고 잘 풀립니다. 그리고 나는 옳은 것을 얻기 위해 각 클래스의 인스턴스를 만들었습니다.동적으로 클래스를로드하고 호출하는 가장 좋은 방법은 무엇입니까

class FileHasher 
{ 
    private readonly List<IHasher> _list; 

    public FileHasher() 
    { 

     _list = new List<IHasher>(); 
     foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) 
     { 
      if(typeof(IHasher).IsAssignableFrom(type) && type.IsClass) 
       _list.Add((IHasher) Activator.CreateInstance(type)); 
     } 

    } 

    public HashReturn GetHashFromFile(string file, HashFileType hashType) 
    { 
     var hashReturn = new HashReturn(); 

     IHasher iHasher = _list.Find(hasher => hasher.HashType == hashType); 

     hashReturn.Hash = iHasher.FileToHash(file); 

     return hashReturn; 
    } 

    public HashReturn GetHashFromString(string str, HashFileType hashType) 
    { 
     var hashReturn = new HashReturn(); 

     IHasher iHasher = _list.Find(hasher => hasher.HashType == hashType); 

     hashReturn.Hash = iHasher.StringToHash(str); 

     return hashReturn; 
    } 


} 

internal class HashReturn 
{ 
    public Exception Error { get; set; } 
    public string Hash { get; set; } 
    public bool Success { get; set; } 
} 

enum HashFileType 
{ 
    CRC32, 
    MD5 
} 

internal interface IHasher 
{ 
    HashFileType HashType { get; } 
    string FileToHash(string file); 
    string StringToHash(string str); 
} 

class MD5Hasher : IHasher 
{ 
    public HashFileType HashType { get { return HashFileType.MD5; } } 

    public string FileToHash(string file) 
    { 
     return ""; 
    } 

    public string StringToHash(string str) 
    { 
     return ""; 
    } 
} 

class CRC32Hasher : IHasher 
{ 
    public HashFileType HashType { get { return HashFileType.CRC32; } } 

    public string FileToHash(string file) 
    { 
     return ""; 
    } 

    public string StringToHash(string str) 
    { 
     return ""; 
    } 
} 
+0

.NET 4에 포함되어 있습니까? 통제 반전? – IAbstract

답변

1

MEF가이 문제를 훌륭하게 해결합니다. http://mef.codeplex.com/

그것은 당신은 의존성 삽입 (Dependency Injection)을 잘 알고

관련 문제