WCF返回包含派生类的基类对象列表

Luc*_*elt 2 c# wcf json

好的,所以我对WCF和C#都很陌生,所以对我来说很光.

我有一个函数返回所有的蛇.看起来像这样,工作正常:

// Function that returns JSON list of snakes
public List<Snake> GetSnakes()
{
    var snakes = new List<Snakes>();
    snakes.Add(new Snake { Length = "10.2" } );
    return snakes;
}
Run Code Online (Sandbox Code Playgroud)

现在我得到了一堆具有不同属性的动物,我不想为它们中的每一个制作一个列表.我想要这样的东西:

public class AnimalService : IAnimalService
{
    private List<Animal> animals = new List<Animals>();

    public List<Animal> getSnakes()
    {
        animals.Add(new Snake { Name = "Snake" } );
        return animals;
    }

    public List<Animal> getPigs()
    {
        animals.Add( new Pig { Weight = "100" } );
        return animals;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.当我将一个派生类添加到我的动物列表中时,WCF服务停止为该函数生成JSON并且不返回任何内容.没有错误或任何结果,但没有结果.我怎样才能实现我的目标?一个包含动物返回集的列表,无论什么类型都无关紧要.

p.s*_*w.g 7

尝试添加KnownTypeAttribute到您的Animal类为每个想拥有系列化的子类:

[DataContract]
[KnownType(typeof(Snake))]
[KnownType(typeof(Pig))]
public class Animal 
{
}
Run Code Online (Sandbox Code Playgroud)