Answer the question
In order to leave comments, you need to log in
C# how to instantiate a class by name in string?
There are several classes, the class name is specified in string, how can I create an instance of the class by this name?
Answer the question
In order to leave comments, you need to log in
var classes = new[]
{
new
{
Name = "System.String",
AssemblyName = "mscorlib",
Args = new object[] { "Single argument".ToCharArray() }
},
new
{
Name = "Newtonsoft.Json.Linq.JObject",
AssemblyName = "Newtonsoft.Json",
Args = new object[] {}
},
new
{
Name = "System.IO.FileInfo",
AssemblyName = "mscorlib",
Args = new object[] { @"C:\Windows\System32\cmd.exe" }
}
};
var instances = classes
.Select(i =>
{
var assembly = Assembly.Load(i.AssemblyName);
var type = assembly.GetType(i.Name);
var instance = Activator.CreateInstance(type, i.Args);
return instance;
})
.ToArray();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question