Does something like a VB “Variant” implementation exist which uses C#'s dynamic dispatch?

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I realize that it goes against the strongly typed nature of C#, but I find that when working with dynamic objects in the language, some of the more useful features typically found in JavaScript or PowerShell are simply not practical.

For example, the following C# code will fail at runtime and it's obvious why.

dynamic x = 1.0; int y = x;

But that makes the dynamic features of C# pretty limited when dealing with loosely typed data such as that produced by JSON payloads or CSV where subtle variations in the representation can result in very different behavior at runtime.

What I'm looking for is something that will behave much like the VBA / VBScript era Variant type. I imagine it's possible to derive such a type from DynamicObject that would wrap primitive values like Int32, String, etc and perform the appropriate casts at runtime. I've done something similar with "null" values in dynamic contexts.

But is there anything like this already established? I've looked around GitHub or Codeplex to no avail but it's kind of a hard thing to search for. Before I get started on what I imagine is going to be quite a complicated class, I want to make sure I'm not wasting my time.

About the practicality of all of this

I should note that I resisted the concept of dynamic dispatch in C# for a long time because it was not intended to be a dynamic language. Quite honestly, I wish it wasn't added to the language at all, or at least restricted to COM interop scenarios.

But having said that, I am always curious about ways to "hack" language features in such a way to make them do things that they were never intended to do. Sometimes something useful comes out of it. For example, there have been plenty of examples of people using the IDisposable interface and using statement to do things that have nothing to do with releasing resources.

I doubt I would use this in production applications or anything that needed to be handed off to another developer.

回答1:

The visual basic languages hide a lot of the glue, that just isn't the C# way. The Variant type has a raft of conversion functions, they are invoked automatically by the vb runtime. .NET has automatic conversion functions too, you just have to use them explicitly:

dynamic x = 1.0; int y = Convert.Int32(x);

With the C# justification for having to write code like that because it is not a language that hides cost.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!