用于读取字节的C#自定义数据转换器[]

时间:2012-12-22 08:14:11

标签: c# c#-4.0

这是我的自定义dataconverter助手类,它帮助我从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[]

0 个答案:

没有答案