因为SqlDataReaderimplements IDataReader,所以它有一个GetChar()方法。但是SqlDataReader,执行那个只是抛出一个NotImplementedException. SqlDataReader被标记为GetChar()在智能感知中不提供,尽管如果您在GetChar()a 的末尾键入SqlDataReader,您会看到它可以编译,但在运行时您会得到NotImplementedException.
一切都相当令人失望,因为在我看来,.Net 团队只需要几行代码就可以实现GetChar().
令人高兴的是,通过使用扩展方法,我们可以将自己的GetChar()方法添加到SqlDataReader. 正如GetChar()已经采取的那样(尽管仅使用 a 实现NotImplmentedException),我们必须将其称为GetChar(). 我叫它GetSingleChar():
internal static class ExtensionMethods
{
internal static char GetSingleChar(this SqlDataReader reader, int columnIndex)
{
System.Data.SqlTypes.SqlChars val = reader.GetSqlChars(columnIndex);
if (val.Length != 1)
{
throw new ApplicationException(
"Expected value to be 1 char long, but was "
+ val.Length.ToString() + " chars long.");
}
return val[0];
}
}