简体   繁体   中英

what is the best way to dynamicly load classes and invoke them

This is what I came up with, but it feels bloated and well, untidy. And I don't like that I have created an instance of each class just to get the right one.

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 "";
    }
}

MEF solves this nicely for you. http://mef.codeplex.com/

It is included in .NET 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM