WCF中的自定义集合类型,如果作为服务契约的一部分进行发布,必须要保证以下几点:
1.集合包含的类型必须使用[Serializable]和[DataContract]标记;
2.集合包含的类型属性必须使用 [DataMember]标记,并且,如果是属性(Property),必须要实现get和set;
3.集合类型必须使用[Serializable]和[CollectionDataContract]标记,以及[KnownType]标记指向集合包含的子类型;
4.集合类型必须实现IEnumerable<T>接口;
5.集合类型使用[DataMember]标记的IList将集合项向客户端公开.
样例如下:
namespace Sharpnessdotnet
{
[Serializable]
[DataContract]
public class Sharpnessdotnet
{
private string name;
[DataMember]
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
[Serializable]
[CollectionDataContract]
[KnownType(typeof(Sharpnessdotnet))]
public class SharpnessdotentCollection : IEnumerable<Sharpnessdotnet>
{
[DataMember]
public IList<Sharpnessdotnet> List;
public SharpnessdotentCollection()
{
List = new List<Sharpnessdotnet>();
}
public void Add(Sharpnessdotnet obj)
{
List.Add(obj);
}
public IEnumerator<Sharpnessdotnet> GetEnumerator()
{
return List.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
}
}
{
[Serializable]
[DataContract]
public class Sharpnessdotnet
{
private string name;
[DataMember]
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
[Serializable]
[CollectionDataContract]
[KnownType(typeof(Sharpnessdotnet))]
public class SharpnessdotentCollection : IEnumerable<Sharpnessdotnet>
{
[DataMember]
public IList<Sharpnessdotnet> List;
public SharpnessdotentCollection()
{
List = new List<Sharpnessdotnet>();
}
public void Add(Sharpnessdotnet obj)
{
List.Add(obj);
}
public IEnumerator<Sharpnessdotnet> GetEnumerator()
{
return List.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
}
}