为什么我需要将对象强制转换为ICryptoTransform
接口以使用方法TransformFinalBlock
接口只是根据MSDN的方法签名,但它看起来像是将对象转换为接口,不仅为新方法提供了新功能,还为其提供了新功能。这是如何工作的?
using (DESCryptoServiceProvider encrypter = new DESCryptoServiceProvider().CreateEncryptor())
{
DES.Key = key;
DES.GenerateIV(); // equivilant to a salt for a hash
byte[] newCipherBytes = ((ICryptoTransform) DES).TransformFinalBlock(clearBytes, 0, clearBytes.Length);
}
DES对象根据intellisense实现ICryptoTransform接口,这意味着它已经实现了TransformFinalBlock方法。
但事实并非如此,无法从DES对象访问此方法。
这是我写的一个工作示例,用于说明具有已实现接口的类的基本用法:
class Program
{
/// <summary>
/// This public interface enforces a method declaration on human, because human implements the interface
/// </summary>
public interface iBirthday
{
DateTime getBirthday();
}
/// <summary>
/// Human implements the interface and the method getBirthday
/// </summary>
public class Human : iBirthday
{
private DateTime birthday = default(DateTime);
private string name = String.Empty;
public Human(string name, DateTime birthday)
{
this.name = name;
this.birthday = birthday;
}
public string getName()
{
return this.name;
}
public DateTime getBirthday()
{
return this.birthday;
}
}
public static void Main()
{
Human james = new Human("James Brown", new DateTime(1933, 5, 3));
Console.WriteLine("{0}'s birthday is on {1}", james.getName(),james.getBirthday());
}
}