如何动态施放对象吗? [英] How can I cast object dynamically?

查看:79
本文介绍了如何动态施放对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定这是问过但不幸的是我发现的唯一的事情是的那不适合我的解决方案。在我目前的项目我做这样的事情:

I am pretty sure this was asked before but unfortunately the only thing I've found was this that was not solution for me. In my current project I do something like:

private object obj;

private void Initialize()
{
    obj.Initialize();
}

private void CreateInstanceA()
{
    obj = Activator.CreateInstance(typeof(MyClassA));
}

private void CreateInstanceB()
{
    obj = Activator.CreateInstance(typeof(MyClassB));
}

这代码并不当然是因为我没有投<$ C工作$ C> OBJ ,因为它的类型是动态变化的。

This code does not work of course because I've not cast obj because its type changes dynamically.

我怎么能投它动态?

推荐答案

三个选项:


  • 如果您可以控制类,你可以让他们实现一个共同的接口,其中包括你的需要,然后做这一切 - 如果你正在使用C#4和.NET 4和转换为界面

  • ,您可以使用动态类型 - 只是声明该变量作为专用动态OBJ; 键,它会编译并找到在执行时正确的方法

  • 否则,使用反射来查找和调用该方法。

  • If you control both classes, and you can make them implement a common interface that includes everything you need, then do that - and cast to the interface
  • If you're using C# 4 and .NET 4, you can use dynamic typing - just declare the variable as private dynamic obj; and it will compile and find the right method at execution time
  • Otherwise, use reflection to find and call the method.

基本上铸造的基础上执行时间类型是没有意义的,因为部分铸造的一点是给的编译的详细信息...你根本就没有在这种情况下。

Basically casting based on an execution time type doesn't make sense, as part of the point of casting is to give the compiler more information... and you simply don't have that in this case.

第一个选项是迄今为止,如果你都不可能实现它的最好的。

The first option is by far the nicest if you can possibly achieve it.

这篇关于如何动态施放对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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