1

这是我的自定义数据转换器帮助器类,它可以帮助我从 DataReader 读取值并返回

  public class DataConvertor<T> where T : IhasIndexer
{
    public DataConvertorField<string, T> String;
    public DataConvertorField<int, T> Int;        
    T reader;

    public void Initialise(T reader)
    {
        this.reader = reader;
        String = new DataConvertorField<string, T>(reader, Convert.ToString);
        Int = new DataConvertorField<int, T>(reader, Convert.ToInt32);

    }
    public bool has(string name)
    {
        try
        {
            object o = reader[name];
            return true;
        }
        catch
        {
            return false;
        }

    }
  }

   public class DataConvertorField<T, O> where O : IhasIndexer
{
    O parent;
    DataConvertorMethod convertor;

    public DataConvertorField(O parent, DataConvertorMethod convertor)
    {
        this.parent = parent;
        this.convertor = convertor;
    }

    public T this[string name]
    {
        get
        {
            if (parent[name] == DBNull.Value)
            {
                if (typeof(T).Equals(typeof(string)))
                    return (T)(object)string.Empty;
                else
                    return default(T);
            }
            else
                return convertor(parent[name]);
        }
    }
    public delegate T DataConvertorMethod(object o);

}

public interface IhasIndexer
{
    object this[string key] { get; }
}

然后我只需在我的ADO.Net 代码中使用如下

  using (DBDataReaderWrapper reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {

                user.UserId = reader.Int["UserId"];
                user.UserName = reader.String["UserName"];
    }

   public class DBDataReaderWrapper : DataConvertor<DBDataReaderWrapper>, 
                                     IDisposable, IhasIndexer
{
    SqlDataReader reader;


    public DBDataReaderWrapper(SqlDataReader reader)
    {
        Initialise(this);
        this.reader = reader;
    }        

    public object this[string name]
    {
        get
        {
            return reader[name];
        }
    }

    public bool Read()
    {
        return reader.Read();
    }

    public bool NextResult()
    {
        return reader.NextResult();
    }

    public void Dispose()
    {
        reader.Close();
        reader.Dispose();

    }

}

}

问题是我如何使用我的帮助类从数据库中读取图像。我想像添加 DataConverter

 public DataConvertorField<byte[], T> Bytes;

在 Initialise() 方法中

 Bytes = new DataConvertorField<byte[]>(reader, Convert.to??????);

我怎样才能做到这一点?任何可满足我需要的 c# 内置或辅助方法?所以我可以像在 ADO.Net 代码中一样使用

 reader.Bytes["UserImage"]; //use custom data covertor and gives bytes[]
4

0 回答 0