动态作为返回类型

发布于 2024-12-11 12:19:38 字数 187 浏览 0 评论 0原文

我遇到的情况是,我需要从方法返回匿名类型的对象,使用dynamic作为返回类型是个好主意吗?需要考虑什么?

public dynamic MyMethod()
{
    // process and return the object of an anonymous type
}

I'm in a situation where I need to return an object of an anonymous type from a method, is it a good idea to use dynamic as a return type? what considerations to take?

public dynamic MyMethod()
{
    // process and return the object of an anonymous type
}

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

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

发布评论

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

评论(3

再浓的妆也掩不了殇 2024-12-18 12:19:38

它没有任何意义,您可以返回具有相同效果的 object

PS:匿名类型也不如返回类型那么好。

It doesn't make any sence, you can return object with the same effect.

P.S.: Also anonymous types are not that good as return types.

十年不长 2024-12-18 12:19:38

是的,它是有意义的如果你“保证”你总是返回一个具有某些特征的对象,例如带有Id(忽略也许使用它会更好)接口)

public dynamic MyMethod()
{
    var temp = new ExpandoObject();
    temp.Id = 5;
    return temp;
}

Console.WriteLine(MyMethod().Id);

因此,如果您保证所有对象都可以左右转动,但不能保证它们是飞机、汽车、摩托车、船。 (所以如果你正在做 鸭子打字 当我看到一只走路的鸟时,那就太好了像鸭子一样游泳,像鸭子一样嘎嘎叫,我称那只鸟为鸭子。

请注意,如果您随后需要反思您的对象,它可能会变得丑陋:如何反映动态对象的成员?

Yes it has sense If you "guarantee" that you'll always return an object with some characteristics , with an Id for example (ignoring that perhaps it would be better to use an Interface)

public dynamic MyMethod()
{
    var temp = new ExpandoObject();
    temp.Id = 5;
    return temp;
}

Console.WriteLine(MyMethod().Id);

So if you guarantee that all your objects can Turn Left-Right but you don't guarantee if they are airplanes, cars, motos, boats. (so it's good if you are doing Duck typing When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.)

Note that if you then need to reflect on your objects, it can become ugly: How do I reflect over the members of dynamic object?

初熏 2024-12-18 12:19:38

返回动态对象确实具有允许您在不使用反射(尽管没有智能感知)的情况下从匿名类型访问属性的好处。如果采用这种方法,您需要确保匿名类型的属性与您在动态对象上访问的属性相匹配。否则你会得到运行时错误

但是,我建议你考虑返回一个具体类型

Returning a dynamic object does have the benifit of allowing you to access the properties from the anonmymous type without using reflection (albeit without intellisense). If you take this approach you need to make sure that the properties on the anonymous type match what you are accessing on the dynamic object. Otherwise you will get runtime errors

However, I would suggest you consider returning a concrete type instead

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