我在序列化过程中遇到了问题。我已经花了很多时间,我找不到解决方案。我有一个类,我想序列化到一个文档集合。如果我班上有四个属性,一切都很棒,但是一旦我添加了另一个属性,我就有了这个例外:
An incorrect number of type args were specified for the declaration of a Func type.
这是我的代码:
class Class1
{
[BsonId]
public ObjectId _id { get; set; }
public string Modelname { get; set; }
public string Sn { get; set; }
public string Filename { get; set; }
public byte[] DataBin { get; set; }
[BsonIgnore]
public MyCustomClass data { get; set; }
[BsonConstructor]
public Class1()
{ }
public Class1(string Modelname, string Sn, string Filename, MyCustomClass data)
{
this.Modelname = Modelname;
this.Sn = Sn;
this.Filename = Filename;
this.data = data;
BinaryFormatter formatter = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, this.data);
this.DataBin = stream.ToArray();
}
}
[BsonConstructor]
public Class1(string Modelname, string Sn, string Filename, byte[] dataBin)
{
this.Modelname = Modelname;
this.Sn = Sn;
this.Filename = Filename;
this.DataBin = dataBin;
BinaryFormatter formatter = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream(this.DataBin))
{
this.data = (MyCustomClass)formatter.Deserialize(stream);
}
}
}
类Class1在我的集合中很好地序列化了。
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase database = server.GetDatabase("mydb");
MongoCollection<Class1> collection = database.GetCollection<Class1>("testCollection");
MyCustomClass data = new MyCustomClass();
Class1 doc = new Class1("test", "sn", "filename", data);
collection.Save<Class1>(doc);
但是,如果我添加另一个属性,则抛出异常:
class Class1
{
[BsonId]
public ObjectId _id { get; set; }
public string Modelname { get; set; }
public string Sn { get; set; }
public string Filename { get; set; }
public double Num { get; set; }
public byte[] DataBin { get; set; }
[BsonIgnore]
public MyCustomClass data { get; set; }
[BsonConstructor]
public Class1()
{ }
public Class1(string Modelname, string Sn, string Filename, double Num, MyCustomClass data)
{
this.Modelname = Modelname;
this.Sn = Sn;
this.Filename = Filename;
this.Num = Num;
this.data = data;
BinaryFormatter formatter = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, this.data);
this.DataBin = stream.ToArray();
}
}
[BsonConstructor]
public Class1(string Modelname, string Sn, string Filename, double Num, byte[] dataBin)
{
this.Modelname = Modelname;
this.Sn = Sn;
this.Filename = Filename;
this.Num = Num;
this.DataBin = dataBin;
BinaryFormatter formatter = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream(this.DataBin))
{
this.data = (MyCustomClass)formatter.Deserialize(stream);
}
}
}
答案 0 :(得分:1)
好的,我发现了这个问题。我尝试使用另一种解决方案在同一台计算机上,一切正常。所以我将代码复制到我的实际解决方案中并且它不起作用:相同的代码,相同的计算机,但结果不同!最后,我意识到我的实际解决方案使用的是.NET 3.5。我将其更改为.NET 4.0,它可以工作!
结论:官方的C#驱动程序据说是在.NET 3.5下构建的,但它在.NET 4.0下运行得更好