C#:动态运行时投 [英] C#: Dynamic runtime cast

查看:139
本文介绍了C#:动态运行时投的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现的方法具有以下签名

I would like to implement a method with the following signature

dynamic Cast(object obj, Type castTo);

任何人都知道该怎么做? OBJ肯定实现castTo但需要才能有我的一些应用程序的运行时绑定的东西制定出正确施放。

Anyone know how to do that? obj definitely implements castTo but needs to be cast properly in order to have some of my app's runtime binding stuff work out.

编辑:如果一些问题的答案没有意义,那是因为我最初不小心输入动态转换(动态OBJ,类型castTo); - 我指的是输入应为对象或其他一些保证基类

If some of the answers don't make sense it's because I initially accidentally typed dynamic Cast(dynamic obj, Type castTo); - I mean the input should be object or some other guaranteed base class

推荐答案

我想你混淆铸造的问题,并在这里转换。

I think you're confusing the issues of casting and converting here.


  • 铸造:不断变化的指向对象的引用类型的行为。无论是上下移动的对象层次结构或实现接口

  • 转换:创建从不同类型的原始来源对象的新对象,并通过该类型的引用访问它。

这往往很难知道在C#中2之间的差别,因为他们都使用相同的C#运算符:中投。

It's often hard to know the difference between the 2 in C# because both of them use the same C# operator: the cast.

在这种情况下,你几乎肯定不会找一个转换操作。铸造动态另一个动态本质上是一种身份的转换。它提供了没有价值,因为你只是得到一个动态引用回到相同的底层对象。由此产生的查找就没有什么不同。

In this situation you are almost certainly not looking for a cast operation. Casting a dynamic to another dynamic is essentially an identity conversion. It provides no value because you're just getting a dynamic reference back to the same underlying object. The resulting lookup would be no different.

相反,你会出现在这种情况下想要的是一个转换。即变形底层的对象不同类型和访问在动态时尚生成的对象。这样做的最好的API是 Convert.ChangeType

Instead what you appear to want in this scenario is a conversion. That is morphing the underlying object to a different type and accessing the resulting object in a dynamic fashion. The best API for this is Convert.ChangeType.

public static dynamic Convert(dynamic source, Type dest) {
  return Convert.ChangeType(source, dest);
}

修改

更新后的问题有以下行:

The updated question has the following line:

OBJ肯定实现castTo

obj definitely implements castTo

如果这是随后的情况下方法不需要存在。源对象可以简单地分配给动态引用。

If this is the case then the Cast method doesn't need to exist. The source object can simply be assigned to a dynamic reference.

dynamic d = source;

这听起来像你想实现什么是看到中通过动态引用。这是根本不可能的。由此产生的动态引用将直接看到的实施对象。它并不通过在源的层次结构的任何特定类型的样子。因此,强制转换为不同类型的层次结构中,然后返回到动态的想法是完全相同的,只是分配给动态在首位。它仍将指向同一个底层对象。

It sounds like what you're trying to accomplish is to see a particular interface or type in the hierarchy of source through a dynamic reference. That is simply not possible. The resulting dynamic reference will see the implementation object directly. It doesn't look through any particular type in the hierarchy of source. So the idea of casting to a different type in the hierarchy and then back to dynamic is exactly identical to just assigning to dynamic in the first place. It will still point to the same underlying object.

这篇关于C#:动态运行时投的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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