我正在编写代码来进行Xml序列化.具有以下功能.
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
如果参数是没有无参数构造函数的类的实例,它将抛出异常.
未处理的异常:System.InvalidOperationException:CSharpConsole.Foo无法序列化,因为它没有无参数构造函数.System.Xml.Serialization.ModelScope.GetTypeModel的System.Xml.Serialization.TypeScope.GetTypeDesc(Type type,MemberInfo sourc e,Boolean directReference,Boolean throwOnError)中的System.Xml.Serialization.TypeDesc.CheckSupported()处于类型类型, System.Xml.Serialization上的System.Xml.Serialization.XmlSerializer..ctor(Type type,String defaultName space)中System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type,XmlRootAttribute root,String defaultNamespace)的布尔直接引用. XmlSerializer..ctor(类型类型)
为什么必须有一个无参数构造函数才能使xml序列化成功?
编辑:感谢cfeduke的回答.无参数构造函数可以是私有的或内部的.
我正在为3种不同的加密类实现工厂模式.工厂将确定要创建哪一个,然后从数据库中获取正确类的序列化实例并将其返回给请求者.现在我正在编写类以将它们存储在数据库中.我正在写一个名为PGP加密类的BouncyCastle.我可以从文件创建类和键,但是当我尝试序列化它时,它表示两个成员变量,它们是类的对象PgpPublicKey,并且PgpPrivateKey由于它们没有无参数构造函数而无法序列化.
public void createdBouncyFromFiles()
{
var bc = new BouncyCastle("C:\\TestFiles\\BouncyPublicKey.txt", "C:\\TestFiles\\BouncyPrivateKey.txt", "Password1");
var xmlSerializer = new XmlSerializer(bc.GetType());
var textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, bc);
var theSerializedClass = textWriter.ToString();
}
Run Code Online (Sandbox Code Playgroud)
该类有两个成员变量是问题.
public class BouncyCastle : ICryptographyProvider
{
public PgpPublicKey m_publicKey;
public PgpPrivateKey m_privateKey;
public string m_passPhrase;
// cut out the irelevant parts
Run Code Online (Sandbox Code Playgroud)
这是公钥类.没有无参数的构造函数.
public class PgpPublicKey
{
public PgpPublicKey(PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time);
// cut other methods
}
Run Code Online (Sandbox Code Playgroud) 由于某种原因,我的一个特定的AJAX调用正在获得"无参数构造函数定义"错误.这是代码:
CallAndReplace(JSON.stringify(model), url, $("#panel"));
function CallAndReplace(data, url, replace) {
$.ajax({
url: url,
type: "post",
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
replace.html(result);
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') …Run Code Online (Sandbox Code Playgroud) 我不明白它是如何工作的:当我实现 ISerializable 接口时,我必须定义 protected(除非类是密封的,在这种情况下,构造函数应该标记为私有)构造函数:
protected MyClass(SerializationInfo info, StreamingContext context)
此访问修饰符使此构造函数无法用于那么项目如何反序列化成功呢?
所以我需要了解哪种方式是正确/最好的方式?
class Customer
{
string firstName;
string lastName;
public Customer(string firstName="non", string lastName="applicable")
{
this.firstName = firstName;
this.lastName = lastName;
}
}
Run Code Online (Sandbox Code Playgroud)
class Customer
{
string firstName;
string lastName;
public Customer()
: this("non","applicable")
{ }
public Customer(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我正在创建一个方法 printFullName(),它在两种情况下都适用。那么选择哪一个呢?第一个对我来说似乎更容易。
c# ×4
constructor ×2
.net ×1
ajax ×1
asp.net ×1
bouncycastle ×1
default ×1
javascript ×1
jquery ×1
parameters ×1