问题描述:

here is my class to serialize/deserialize.

public class MyDic

{

...

[XmlElement(IsNullable = true)]

public List<WebDefinition> WebDefinitions;

...

}

and it's a full definition of the struct WebDefinition.

public struct WebDefinition

{

public string Definition;

public string URL;

public WebDefinition(string def, string url)

{

Definition = def;

URL = url;

}

public override string ToString() { return this.Definition; }

}

i expected Dictionary.WebDefinitions can nullable when deserialzation. but it occured a runtime error when

//runtime error : System.InvalidOperationException

XmlSerializer myXml = new XmlSerializer(typeof(Dictionary), "UOC");

why i can't use XmlElementAttribute.IsNullable?

note1:

when i delete a line [XmlElement(IsNullable = true)], it works properly with no error.(serialization and deserialization).

note2:

exception is System.InvalidOperationException and message is : "error occured in during reflection 'UOC.DicData' type"

thanks.

网友答案:

As I indicated in the comment "and in particular the InnerException"; since you didn't add this, I ran the sample, and the innermost InnerException is:

IsNullable may not be 'true' for value type WebDefinition. Please consider using Nullable<WebDefinition> instead.

That tells you everything you need, I think. Changing it to WebDefinition? (aka Nullable<WebDefinition> does indeed fix it.

But key point here: read the exception and the InnerException.

IMO, a better "fix" here is to make it a class; since WebDefinition is not a "value", it has no business being a struct (and in particular a struct with public mutable fields is ... evil):

public class WebDefinition
{
    public WebDefinition(){} // for XmlSerializer
    public string Definition { get; set; }
    public string URL { get; set; }
    public WebDefinition(string def, string url)
    {
       Definition = def;
       URL = url;
    }
    public override string ToString() { return this.Definition; }
}
网友答案:

If you are using C# 4.0 did you try

public class MyDic
{
    ...

    public List<WebDefinition?> WebDefinitions;  //note the ? after your type.                    

    ...
}

Oops I meant to remove the xelementnull part. So a List can be null itself so I am assuming you are trying to allow WebDefinition to be null as well.Using the "?" will allow it to be a nullable type.. it pretty much is doing what your attribute is doing.

You can do this with ints also.. decalre an int like public int? myInt = null; and it will work.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx

相关阅读:
Top