ASP.NET Web服务对象操作

发布于 2024-10-31 14:24:32 字数 390 浏览 1 评论 0原文

可能不是特定于 Web 服务,但是...

我有一个返回的 Web 方法:

List<Tadpole> myList = getList();

return new { data = myList , count = 5 };

它以 JSON 形式返回。

我的代码检查 myList[x].fishsticks 它实际上不是 Tadpole 类的一部分(因此会出错)。我想知道,我可以在 myList 中添加一个 fishsticks 属性来避免错误,这样当我返回数据时它就会被包含在内吗?

是否有另一种优雅的解决方案可以做到这一点?

Possibly not specific to webservices, but...

I have a webmethod that returns:

List<Tadpole> myList = getList();

return new { data = myList , count = 5 };

It returns this as JSON.

my code checks myList[x].fishsticks which isn't actually part of the Tadpole class (so it errors). I am wondering, can I add a fishsticks attribute to myList somehow to avoid the error, so it gets included when I return the data?

Is there perhaps another elegant solution for doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独患者 2024-11-07 14:24:32

在您的示例中,您必须向 Tadpole 添加一个 fishsticks 属性。

public class Tadpole
{
    //....
    public int Fishsticks { get; set; } 
}

另外,为什么要向 JSON 类型添加 .Count 属性?仅 .data.Count 或仅返回列表并完全跳过包装器不是更有意义吗?

我还没有检查 List<> 的哪些属性最近被序列化,因此它可能不包括在内,但即使是这种情况,这样做也更有意义:

List<Tadpole> myList = getList();

return new { data = myList , count = myList.Count };

或者,创建一个重写 .Count 并添加序列化属性的后代类。

编辑

如果我没记错的话,匿名/动态类型在内部实现为字典,而类则不是。 (顺便说一句,匿名类型和动态对象带来了许多性能和维护问题。)

如果您出于某种原因不想修改 Tadpole,您总是可以创建一个后代类:

public class HungryTadpole : TadPole
{
    public int FishSticks { get; set; } 
}

强类型是您的朋友,并且会节省今后您可能会遇到许多令人头疼的问题。

In your example, you'll have to add a fishsticks property to Tadpole.

public class Tadpole
{
    //....
    public int Fishsticks { get; set; } 
}

Also, why are you adding a .Count property to your JSON type? Wouldn't it make more sense to just .data.Count, or just return the list and skip the wrapper entirely?

I haven't checked what properties of List<> get serialized lately, so it's possible that it's not included, but even if that's the case it would make more sense to do this:

List<Tadpole> myList = getList();

return new { data = myList , count = myList.Count };

Or, create a descendant class that overrides .Count and adds a serialization attribute.

Edit

If I remember correctly, anonymous/dynamic types are internally implemented as dictionaries, while classes are, well, not. (BTW, anonymous types and dynamic objects bring a host of performance and maintenance issues along with them.)

If you don't want to modify Tadpole for some reason, you could always create a descendant class:

public class HungryTadpole : TadPole
{
    public int FishSticks { get; set; } 
}

Strong typing is your friend and will save you many headaches down the road.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文