开发者

WCF and various return classed

I've come onto a problem which I can't find a good solution to - I've got a WCF service, where I want to return an object of ChildClass which inherits from FatherClass.

Mostly, I'd return the ChildClass, but in some cases I'd like to return just the FatherClass (which holds just 1 field "error").

Can this be accomplished?

My Code:

[WebGet(UriTemplate = "SomeQueryString", Resp开发者_Go百科onseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
public ChildClass GetCollection(parameter)
{

    if (err)
    {
        return new FatherClass();
    }
    else
    {
        return new ChildClass();
    }
}

Where as ChildClass inherits from FatherClass (has less fields).

My objective is to return only a very small fraction of the "text" instead of the text that will be returned if I return the whole ChildClass object.

Ideas? :)

Thanks!


That is possible only if you redefine your operation and contracts - you must return parent and serializer must know about all children which can be used instead of the parent:

[KnownType(typeof(ChildClass)]
[DataContract]
public class ParentClass 
{
    // DataMembers
}

[DataContract]
public class ChildClass : ParentClass 
{
    // DataMembers
}

And your operation will look like:

[WebGet(UriTemplate = "SomeQueryString", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
public ParentClass GetCollection(parameter)
{
    ...
}


I think this is a question about C# and type casting. As you have it, it won't work because ChildClass : FatherClass. See below:

    class FatherClass
    {
        public int x { get; set; }
    }

    class ChildClass : FatherClass
    {
        public int y { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            FatherClass a = new FatherClass();
            ChildClass b = new ChildClass();


            FatherClass c = (FatherClass)b;
            ChildClass d = (ChildClass)a;

            Console.ReadLine();
        }
    }

The cast ChildClass d = (ChildClass)a; will fail. So you could try modifying your signature to

public FatherClass GetCollection(parameter)

and use appropriate type casting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜