与Activator.CreateInstance创建工作对象 [英] Working with objects created with Activator.CreateInstance

查看:150
本文介绍了与Activator.CreateInstance创建工作对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

void fun1(string typeName)
{
    object adap = Activator.CreateInstance(typeName);
    adap.dowork(); //won't compile because of strongly typed.
}

使用 Activator.CreateInstance(),我们可以轻松地创建任何类型的实例,但如果我们不知道在设计时的类型名称,它是没有可能垂头丧气其实际类型无论是。

Using Activator.CreateInstance() we can easily create instance of any type, but if we don't know the typename at design time, it is not possible downcast it to its actual type either.

我的问题是,我们怎么能叫例如,通过 Activator.CreateInstance 创建如果我们不能将其向下转换其相应类型的功能,因为我们不知道在设计时的类型名,但我们知道该函数存在。

My question is, how can we call a function of instance created by Activator.CreateInstance if we cant downcast it to its appropriate type as we dont know the typename at design time, but we know that the function exists.

我希望我已经说清楚了。

I hope I've made myself clear.

推荐答案

有一件事你可以做的是将其分配到 A 动态类型。

One thing you can do is assign it to a dynamic type.

dynamic adap = Activator.CreateInstance(typeName);
adap.dowork(); //this now compiles



也可以调用方法使用动态反映,如果你知道方法名称。

It is also possible to invoke a method dynamically using reflection if you know the method name.

这篇关于与Activator.CreateInstance创建工作对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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