使用C#反射调用构造函数
我有以下情况:使用C#反射调用构造函数,c#,reflection,constructor,C#,Reflection,Constructor,我有以下情况: class Addition{ public Addition(int a){ a=5; } public static int add(int a,int b) {return a+b; } } 我正在通过以下方式调用另一个类中的外接程序: string s="add"; typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22 我需要一种类似于上述反射语句的方法
class Addition{
public Addition(int a){ a=5; }
public static int add(int a,int b) {return a+b; }
}
我正在通过以下方式调用另一个类中的外接程序:
string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22
我需要一种类似于上述反射语句的方法,使用Addition(inta)
所以我有strings=“Addition”
,我想使用反射创建一个新对象
这可能吗?是的,你可以使用我不认为
GetMethod
可以做到这一点,不-但是会
编辑:是的,
Activator.CreateInstance
也可以工作。使用GetConstructor
如果你想对事情有更多的控制权,请找出参数名称等。Activator.CreateInstance
如果你只想调用构造函数就很好。是的,但是你必须实现所有重载解析规则来选择正确的构造函数。然而,如果您要缓存委托(多次调用同一个构造函数时会提高性能),那么运行时将为您提供帮助,因此GetConstructor
是首选方法,但是对于一次性使用Activator
会更容易。@AkshayJoy:“它的ot工作”几乎没有足够的信息。我已经告诉过你如何进行机械转换——另一种方法是确保你理解C代码,然后确保你知道构造数组的VB语法。如果这是一个太多的挑战,那么你就应该真正远离反射。明白了,感谢Jon Skeet Dim params(0)As Type params(0)=GetType(FViewer)Dim ConstructorInfo obj As ConstructorInfo=objType.GetConstructor(params)@SarathAvanavu:无论如何,你不会用反射来做那件事。。。现在还不清楚你在谈论什么情况,所以可能值得问一个新问题(当然,在搜索了类似的问题之后)。你为什么要使用反射?反射会带来性能损失,从长远来看会造成维护问题…@Patrick,在很多情况下,只要用户目标实现,性能损失就可以忽略。这确实需要一个恰当的答案有趣的是,似乎当构造函数有参数时,那么反射比Activator.CreateInstance:@KallDrexx:benchmark没有正确测量反射的成本,因为大部分反射都是在测量的函数之外完成的。移动typeof(Program).GetConstructor(new[]{typeof(int)})调用它以进行更公平比较的函数中的code>。即使这样,您也提前选择了精确匹配的重载,而Activator
必须使用相同数量的参数跨所有构造函数执行重载解析。@BenVoigt如果为true,则如果刷新,您将看到一个新的测试,其中我添加了此测试用例。即使考虑到GetConstructor()
调用的时间,它仍然是ACtivator.CreateInstance的2/3倍。我也不认为Activator.CreateInstance缓存它可能引起的任何反射调用是不合理的(因为它可以被再次调用),但不管它的代价是什么,它显然没有。
using System;
using System.Reflection;
class Addition
{
public Addition(int a)
{
Console.WriteLine("Constructor called, a={0}", a);
}
}
class Test
{
static void Main()
{
Type type = typeof(Addition);
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 10 });
}
}