The program does si开发者_高级运维milar things again and again. I want to reduce the code I use. It's an example, in this example it is not needed but I will do another thing similar in the future. Now I'm confused and said "Why should I copy the same codes one by one?"
But I get 'Object' does not contain a definition for 'ComputeHash' error. In runtime they won't be objects, they are classes. So they don't have the same variable type. What should I do?
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "ALL files(*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = String.Empty;
var list = new ArrayList() { crc32, md5, sha1 };
foreach (var checksum in list)
{
using (FileStream fs = File.Open(op.FileName, FileMode.Open))
{
foreach (byte b in checksum.ComputeHash(fs))
{
hash += b.ToString("x2").ToLower();
}
textBox1.Text += hash + "\r\n";
hash = String.Empty;
}
}
}
}
It's because you're using the non-generic ArrayList
type. If you change it to:
var list = new List<HashAlgorithm> { crc32, md5, sha1, ... };
it'll be fine. Basically, the compile-time type of checksum
is currently object
, not HashAlgorithm
.
You should use strongly typed collections whenever you can.
(You should also use using
statements for streams - currently you're not closing the stream.)
精彩评论