有没有办法在 C# 中进行动态隐式类型转换? [英] Is there a way to do dynamic implicit type casting in C#?

查看:29
本文介绍了有没有办法在 C# 中进行动态隐式类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个带有隐式转换运算符的类:

Given this class with an implicit cast operator:

public class MyDateTime
{
    public static implicit operator MyDateTime(System.Int64 encoded)
    {
        return new MyDateTime(encoded);
    }

    public MyDateTime(System.Int64 encoded)
    {
        _encoded = encoded;
    }
    System.Int64 _encoded;
}

我现在可以执行以下操作:

I can now do the following:

long a = 5;
MyDateTime b = a;

但不是以下:

long f = 5;
object g = f;
MyDateTime h = g;

这给出了编译时间:

无法将类型object"隐式转换为MyDateTime".

Cannot implicitly convert type 'object' to 'MyDateTime'.

对我来说很有意义.

现在我把前面的例子修改如下:

Now I modify the previous example as follows:

long f = 5;
object g = f;
MyDateTime h = (MyDateTime)g;

这编译得很好.现在我得到一个运行时 InvalidCastException:

This compiles fine. Now I get a runtime InvalidCastException:

无法将System.Int64"类型的对象转换为 MyDateTime"类型.

Unable to cast object of type 'System.Int64' to type MyDateTime'.

这告诉我,C# 隐式转换运算符仅在编译时应用,而不是在 .NET 运行时尝试将对象动态转换为另一种类型时应用.

This tells me that C# implicit cast operators are applied at compile time only, and are not applied when the .NET runtime is attempting to dynamically cast an object to another type.

我的问题:

  1. 我说的对吗?
  2. 还有其他方法可以做到这一点吗?

顺便说一句,完整的应用程序是我使用 Delegate.DynamicInvoke() 来调用一个带有 MyDateTime 参数的函数,以及我传递给 DynamicInvoke 的参数很长.

By the way, the full application is that I'm using Delegate.DynamicInvoke() to call a function that takes a MyDateTime parameter, and the type of the argument I'm passing to DynamicInvoke is a long.

推荐答案

我说的对吗?

是的,是的,你是.为了挑剔,您应该说用户定义的隐式转换"而不是隐式转换"——转换(几乎)总是显式的.但是您关于重载解析选择在编译时调用哪个用户定义的转换而不是在运行时调用 的推断是正确的.

Yes, yes you are. To be nit-picky, you should be saying "user-defined implicit conversion" rather than "implicit cast" -- a cast is (almost) always explicit. But your deduction that overload resolution chooses which user-defined conversion to call at compile time and not at run time is correct.

还有其他方法可以做到这一点吗?

Is there some other way to do this?

是的.在 C# 4 中,如果您将对象"键入为动态",那么我们在运行时再次启动编译器并重新对操作数执行所有分析,就像它们的编译时类型一样是当前的运行时类型.正如您可能想象的那样,这并不便宜,尽管如果您在一个紧密的循环中执行此操作,我们会非常聪明地缓存和重用结果.

Yes. In C# 4 if you type your "object" as "dynamic" then we start up the compiler again at runtime and re-perform all the analysis on the operands as though their compile-time types were the current run-time types. As you might imagine, this is not cheap, though we are very smart about caching and re-using the results should you do this in a tight loop.

这篇关于有没有办法在 C# 中进行动态隐式类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆