我有一个 NHibernate IUserType,我试图用它来将几个固定大小的 double[] 字段(不同大小)绑定到单个数据库列作为 BLOB。我有以下代码,但不知何故我需要将一个常量整数传递给它,以便它知道数组应该有多大。我认为没有办法在运行时以自定义方式实例化这种类型,因此大小确实需要成为类型本身的一部分。如果我可以避免的话,我宁愿没有这个丑陋课程的两个副本!
public class DoubleArrayUserType<Size> : NHibernate.UserTypes.IUserType
{
private int _size = sizeof(Size);
public object Assemble(object cached, object owner)
{
if (cached == null)
return null;
if (cached == DBNull.Value)
return null;
if (!(cached is byte[]))
throw new ArgumentException();
var arrayBytes = cached as byte[];
var arrayStream = new BinaryReader(new MemoryStream(arrayBytes));
var values = new double[_size];
for (int i = 0; i < _size; ++i)
values[i] = arrayStream.ReadDouble();
return values;
}
public object Disassemble(object value)
{
if (value == null)
return DBNull.Value;
if (value == DBNull.Value)
return DBNull.Value;
if (!(value is double[]))
throw new ArgumentException();
var values = value as double[];
var bytes = new List<byte>(sizeof(double) * _size);
for (int i = 0; i < _size; ++i)
bytes.AddRange(BitConverter.GetBytes(values[i]));
return bytes.ToArray();
}
public NHibernate.SqlTypes.SqlType[] SqlTypes
{
get { return new NHibernate.SqlTypes.SqlType[] { NHibernate.SqlTypes.SqlTypeFactory.GetBinaryBlob(1) }; }
}
}