gpt4 book ai didi

c# - 如何使用 Activator.CreateInstance 来反射(reflect)其构造函数参数仅与 ref 不同的类型

转载 作者:行者123 更新时间:2023-12-05 04:16:28 30 4
gpt4 key购买 nike

如何在调用特定构造函数时使用反射创建下面类型的实例?检查了 Activator.CreateInstance 的所有重载,但认为没有匹配项。在下面的示例中,我希望在创建 SomeType 的实例后将 x 加倍,即我希望调用采用 ref int 版本的构造函数。

另外,MS 是如何为 CreatInstance 方法定义“最佳匹配”算法的?

internal sealed class SomeType
{

//consturctor with non-reference parameter
public SomeType(int x)
{
x *= 3;
}

//constructor with reference parameter
public SomeType(ref int x)
{
x *= 2;
}
}

class Program
{
private static void main()
{
var param = new object[] {4}; // constructor parameter
Console.WriteLine("Param Before consturctor called: " + param[0]);
Object instance = Activator.CreateInstance(typeof(SomeType), param);
Console.WriteLine("Param after constuctor called: " + param[0]);
}
}

最佳答案

为了匹配ref int x 参数,您可以使用Type.GetConstructor 创建一个实例并将其传递给System.Int32&作为参数:

var ctor = typeof(SomeType).GetConstructor(new[] { Type.GetType("System.Int32&") });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

编辑:

正如@mikez 所建议的,使用 typeof(int).MakeByRefType() 而不是 System.Int32& 会更好:

var ctor = typeof(SomeType).GetConstructor(new[] { typeof(int).MakeByRefType(); });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

关于c# - 如何使用 Activator.CreateInstance 来反射(reflect)其构造函数参数仅与 ref 不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469302/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com