2011-10-07 51 views
39

当我写这样的代码非序列化物业

[XmlIgnore] 
[NonSerialized] 
public List<string> paramFiles { get; set; } 

我收到以下错误:

Attribute 'NonSerialized' is not valid on this declaration type. 
It is only valid on 'field' declarations. 


如果我写

[field: NonSerialized] 

我得到以下警告

'field' is not a valid attribute location for this declaration. 
Valid attribute locations for this declaration are 'property'. 
All attributes in this block will be ignored. 


如果我写

[property: NonSerialized] 

我得到以下错误(再次):

Attribute 'NonSerialized' is not valid on this declaration type. 
It is only valid on 'field' declarations. 


我怎样才能在财产使用[NonSerialized]

+0

可能的重复[如何将属性标记为不可序列化的json?](http://stackoverflow.com/questions/5103200/how-to-mark-a-property-as-non-serializable-for- json) –

回答

42

好...第一个错误告诉你不能.. 从http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

[AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)] 
[ComVisibleAttribute(true)] 
public sealed class NonSerializedAttribute : Attribute 

我建议使用支持字段

public List<string> paramFiles { get { return list;} set { list = value; } } 
[NonSerialized] 
private List<string> list; 
+9

使用建议的后台字段似乎不起作用。该物业仍在序列化。 –

+0

是的,但它并不适用于每个名为AaaSerializer的类。你在使用哪个序列化程序? – wiero

+2

正确的属性是[NonSerialized],而不是[NonSerializable] –

52

简单的使用:

[XmlIgnore] 
[ScriptIgnore] 
public List<string> paramFiles { get; set; } 

希望它有帮助。

+2

事实上,这甚至可以在传统的ASP.NET Web服务场景中完全隐藏来自消费者的属性名称(对于那些陷入WCF项目之前的人来说这是一个很棒的技巧) – timmi4sa

+0

非常感谢你,这是完美的 – Mik1893

+0

我不需要使用[ScriptIgnore]使这项工作 –