gpt4 book ai didi

c# - 动态加载类并调用它们的最佳方法是什么

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:25 26 4
gpt4 key购买 nike

这是我想出的,但感觉臃肿,不整洁。而且我不喜欢我为每个类创建一个实例只是为了获得正确的实例。

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 可以很好地为您解决这个问题。 http://mef.codeplex.com/

它包含在 .NET 4 中。

关于c# - 动态加载类并调用它们的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com