问题描述
我看过有关如何将字符串转换为类类型的示例,但是我无法将相同的逻辑应用于具有构造函数的类,该构造函数本身将字符串作为参数.这是我在其他帖子上看到的.
I have seen examples on how to convert string to class type, but I was unable to apply the same logic to a class that has a constructor, which itself takes a string as a parameter. This is what I have seen on other posts.
Type type = Type.GetType("classNameAsString");
object instance = Activator.CreateInstance(type);
我想做的是将同样的方法应用到这个案例中
What I want to do is to apply the same to this case
public class ExampleClass
{
public ExampleClass(string strParameter)
{
}
}
我通常会将 ExampleClass 实例化为
I would normally instantiate ExampleClass as
var exClassInst = new ExampleClass("stringParam");
我怎样才能实现相同的目标,但首先将ExampleClass"字符串转换为类型,然后实例化它.感谢您的帮助.
How can I achieve the same, but first converting "ExampleClass" string to type and then instantiating it. Thank you for your help.
推荐答案
您仍然可以使用 Activator
但使用带有构造函数参数的 CreateInstance
重载:
You still can use Activator
but using CreateInstance
overload with the constructor arguments:
Type type = Type.GetType("Namespace.ExampleClass");
object instance = Activator.CreateInstance(type, "string param");
这篇关于C# 将字符串转换为具有带字符串参数的构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!