在数据绑定期间是强制转换和对象还是使用动态更好
我想我很好奇什么更好? 将 DataItem 转换为我知道的类型... 或者 将对象传递给需要 Dynamic 的函数,然后让 DLR 发挥其魔力。
<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
<div>
<%# FormatBlogLink(Container.DataItem) %>
OR
<%# FormatBlogLink((BlogPost)Container.DataItem) %>
</div>
</ItemTemplate>
</asp:Repeater>
代码
protected string FormatBlogLink(dynamic blogPost)
{
/// Do a bunch of stuff
}
对比:
protected string FormatBlogLink(BlogPost blogPost)
{
/// Do a bunch of stuff
}
我的例子很简单, 我以为我读到 DLR 会缓存它所查看的内容,所以它, 所以我很好奇,对于较大的数据源来说最糟糕的是什么......大量转换还是大量使用动态? (或者)我有点疯狂......:)
I guess I am curious what is better?
Casting the DataItem to the type i know it is...
Or
pass the object to a function that expects a Dynamic, and let the DLR do its magic.
<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
<div>
<%# FormatBlogLink(Container.DataItem) %>
OR
<%# FormatBlogLink((BlogPost)Container.DataItem) %>
</div>
</ItemTemplate>
</asp:Repeater>
Code
protected string FormatBlogLink(dynamic blogPost)
{
/// Do a bunch of stuff
}
vs:
protected string FormatBlogLink(BlogPost blogPost)
{
/// Do a bunch of stuff
}
My example is simple,
I thought i read that the DLR will cache things it looked at so it,
so I am curious, what is worst for larger data sources... lots of casting or lots of using dynamic?
(or) am i a bit crazy ... :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人的意见是转换为适当的类型(如果您希望使用该类型)。在
FormatBlogLink
中使用dynamic
的唯一原因是,如果您希望传递恰好共享相同属性名称和方法等的不同对象。否则,请强制转换为适当的类型并受益于智能感知。My personal opinion would be to cast to the appropriate type, if that is what you are expecting to use. The only reason to use
dynamic
in yourFormatBlogLink
is if you expect to pass different objects that just happen to share the same property names and methods, etc. Otherwise, cast to the appropriate type and benefit from intellisense.我也会选择强制转换 - 但你可以在 FromatBlockLink - 方法中执行此操作(让它接受对象)。这样做的优点是您可以从视图中删除这个(小)逻辑,当然您可以检查函数中的类型。
I too would opt for the cast - but you can do this in your FromatBlockLink - method (let it take object). This has the advantage that you remove this (little) logic from your view and of course you can check the type in your function.