首先,我仍在学习面向对象编程。好的,我有一个组合框,里面有不同类型的对称算法。
private void Form3_Load(object sender, EventArgs e)
{
openencrypt();
comboBox1.Items.Add("AES");
comboBox1.Items.Add("DES");
comboBox1.Items.Add("Rijndael");
comboBox1.Items.Add("RC2");
comboBox1.Items.Add("Triple DES");
comboBox1.SelectedIndex = 0;
}
然后我让我的加密函数检查它们是什么类型。
byte[] hpass;
string nFilepath = Set.nfilepath;
FileStream Open = new FileStream(oFilepath, FileMode.Open, FileAccess.Read);
FileStream Save = new FileStream(nFilepath, FileMode.OpenOrCreate, FileAccess.Write);
SHA512 sh512 = new SHA512Managed();
hpass = sh512.ComputeHash(Encoding.ASCII.GetBytes(textBox1.Text));
PasswordDeriveBytes pdb = new PasswordDeriveBytes(hpass, hash);
if (comboBox1.SelectedIndex.Equals(0))
{
Aes alg = Aes.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
}
if (comboBox1.SelectedIndex.Equals(1))
{
DES alg = DES.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
}
if (comboBox1.SelectedIndex.Equals(2))
{
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
}
但当我不想在每个if语句中放入加密流时。那么,有没有一种方法可以将检查卸载到函数并返回对称算法类型?用钥匙和静脉注射?我是不是完全错了?##标题##
一种更面向对象的方法是:
创建一个显示在组合框中的算法界面:
public interface IAlgorithmItem
{
SymmetricAlgorithm CreateAlgorithm();
string DisplayName { get; }
}
然后,为每个所需的算法创建一个新的类:
public class AesAlgorithm : IAlgorithmItem
{
public AesAlgorithm()
{
}
public SymmetricAlgorithm CreateAlgorithm()
{
return Aes.Create();
}
public string DisplayName
{
get { return "AES"; }
}
}
public class RijndaelAlgorithm : IAlgorithmItem
{
public SymmetricAlgorithm CreateAlgorithm()
{
return Rijndael.Create();
}
public string DisplayName
{
get { return "Rijndael"; }
}
}
// ...
然后,您可以创建一个新的项目列表:
var listItems = new List<IAlgorithmItem>() { new AesAlgorithm(), new RijndaelAlgorithm() };
然后你可以将你的组合框绑定到这个列表:
comboBox1.DataSource = listItems;
comboBox1.DisplayMember = "DisplayName";
稍后,您可以参考所选项目:
var algorithmItem = (IAlgorithmItem)comboBox1.SelectedItem;
var algorithm = algorithmItem.CreateAlgorithm();
编辑:根据Will关于使用接口而不是抽象基类的建议进行了更新。编辑2:更新为使用创建方法而不是属性,因为每次访问操作的结果都会创建一个新算法。
好吧,我的第一个倾向是在维基百科上给你提供工厂方法和抽象工厂模式的链接(在那里,我仍然这样做了),但既然你说你是初学者,我们就不要提前大做文章了。
基本上,您需要的是找到所有加密算法的共同特征,并创建一个方法来返回具有该共同特征的对象实例。这种特性的表现可以是一个抽象类,也可以是C#中的一个接口,幸运的是,你选择的所有加密都源自SymmetricAlgorithm("幸运"可能是对System.Security.Cryptography设计者的侮辱,但为了说明起见,我相信他们会原谅我的;)。
因此,只需通过引入一种新方法来重构代码,可能如下所示:
private SymmetricAlgorithm GetAlgorithm(int index)
{
switch (index)
{
case 0:
return Aes.Create();
case 1:
return DES.Create();
case 2:
return Rijndael.Create();
default:
throw new NotSupportedException("unknown algorithm");
}
}
您可以很容易地从代码的其余部分中找出如何使用这个新方法。