Wat*_* v2 5 .net c# reflection system.reflection
sTypeName = ... //do some string stuff here to get the name of the type
/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to
the type whose name is sTypeName.
assembly.CreateInstance(sTypeName)
So, in effect I want to do something like:
*/
assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);
Run Code Online (Sandbox Code Playgroud)
我怎么做?并且,假设这是C#2.0,我在赋值表达式的左侧做什么.我没有var关键字.
通常你让所有想要动态实例化的类实现一个公共接口,比如说IMyInterface。您可以从类名字符串创建一个实例,如下所示:
Assembly asm = Assembly.GetExecutingAssembly();
string classname = "MyNamespace.MyClass";
Type classtype = asm.GetType(classname);
// Constructor without parameters
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype);
// With parameters (eg. first: string, second: int):
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype,
new object[]{
(object)"param1",
(object)5
});
Run Code Online (Sandbox Code Playgroud)
即使您没有通用接口,但知道方法的名称(作为字符串),您也可以像这样调用方法(属性、事件等非常相似):
object instance = Activator.CreateInstance(classtype);
int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance,
new object[] { 15 });
// result = 30
Run Code Online (Sandbox Code Playgroud)
示例类:
namespace MyNamespace
{
public class MyClass
{
public MyClass(string s, int i) { }
public int TwoTimes(int i)
{
return i * 2;
}
}
}
Run Code Online (Sandbox Code Playgroud)