C# 的“动态”在 F# 中
在 C# 中使用 DLR 的一个示例如下:
dynamic dyn = new MyObject();
dyn.MyMethod(); //resolved at runtime
F# 中的等效项是什么?
谢谢。
One example of using the DLR in C# is as follows:
dynamic dyn = new MyObject();
dyn.MyMethod(); //resolved at runtime
what would be the equivalent in F#?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
?
运算符与 C# 中的dynamic
关键字具有类似的表达能力(但它只能用于读取属性、方法调用和设置属性)。没有允许您动态使用 .NET 类的属性或方法(通过反射或 DLR)的内置实现,但社区中有一些相当可靠的实现。这已经在之前的另一个SO问题中讨论过。
还有
?
的实现允许您访问一些常见的数据源,例如 SQL 数据库。例如,这篇 MSDN 文章包含一个定义,允许您编写db?Query?Foo(1)
调用名为Foo
的存储过程。对于各种其他类型(例如在 XAML 中查找元素或访问 XML 文档中的元素或属性),
?
的定义非常容易编写。The
?
operator has similar expressive power to thedynamic
keyword in C# (but it can be only used for reading of properties, method invocation and setting of properties).There is no built-in implementation that would allow you to dynamically use properties or methods of a .NET class (via Reflection or DLR), but there are some fairly solid implementations from the community. This has been discussed in another SO question before.
There are also implementations of
?
that allow you access some common data sources such as SQL databases. For example, this MSDN article includes a definition that allows you to writedb?Query?Foo(1)
to call a stored procedure namedFoo
.For various other types (such as finding an element in XAML or accessing elements or attributes in XML document), the definition of
?
is quite easy to write.另一方面,如果您尝试从 F# 向 C# 公开动态行为,则可以使用
DynamicAttribute
[MSDN]。例如,声明一个动态属性可能看起来像在 C# 中使用的那样
On the flip side, if you're trying to expose
dynamic
behavior to C# from F#, you can useDynamicAttribute
[MSDN]. For example, declaring a dynamic property might look likewhich is used from C# like
有一个名为
FSharp.Interop.Dynamic
的包这样就可以使用?
运算符调用动态对象。There's a package called
FSharp.Interop.Dynamic
and that will make it possible to do a call to a dynamic object using the?
operator.F# 有 ?您使用的运算符如下所示:
没有等效的动态关键字。看看这篇文章如何使用它 https://weblogs.asp.net/podwysocki/using-and-abusing-the-f-dynamic-lookup-operator
F# has the ? operator which you use like so:
There is no dynamic keyword equivalent. Take a look at this article for how to use it https://weblogs.asp.net/podwysocki/using-and-abusing-the-f-dynamic-lookup-operator