使用构造函数实例化反射对象

时间:2016-11-03 09:50:08

标签: c#

我使用反射创建一个类对象的实例并调用该类中的方法:

    // Get ExportLines type
    Type type = typeof(ExportLines);

    // Create an instance of ExportLines type
    object obj = Activator.CreateInstance(type);

    // Retrieve the variable method name from ExportLines
    MethodInfo methodInfo = type.GetMethod("ExportLine_" + ExportLineNumber.ToString());

    // Invoke the method on the instance created above with _Data object parameter
    var val = methodInfo.Invoke(obj, new object[] { _Data, dataStrings});

    //Add to txt file (later)
    return val.ToString();

正如您所看到的那样,我正在使用几个参数调用该方法,我真正想要做的是初始化类并使用这些参数并设置一个全局变量,以便在此期间的所有方法中使用类实例。

这可能吗?

感谢。

1 个答案:

答案 0 :(得分:0)

因此,您应该将ExportLines类添加一个构造函数作为参数,接受_DatadataStrings。此构造函数应确保在ExportLine_n方法中保存传递的参数以供以后使用。现在,您可以使用Activator.CreateInstance Method (Type, Object\[])重载,该重载使用与指定参数最匹配的构造函数创建指定类型的实例。

相关问题