简体   繁体   中英

C# creating instance of class and set properties by name in string

I have some problem. I want to creating instance of class by name. I found Activator.CreateInstance http://msdn.microsoft.com/en-us/library/d133hta4.aspx and it works fine, and I found this: Setting a property by reflection with a string value too.

But how to do both od this? I mean, I know the name of class, I know all properties in that class and I have this in string. For example:

string name = "MyClass";
string property = "PropertyInMyClass";

How to create instance and set some value to properties ?

You could use Reflection:

using System;
using System.Reflection;

public class Foo
{
    public string Bar { get; set; }
}

public class Program
{
    static void Main()
    {
        string name = "Foo";
        string property = "Bar";
        string value = "Baz";

        // Get the type contained in the name string
        Type type = Type.GetType(name, true);

        // create an instance of that type
        object instance = Activator.CreateInstance(type);

        // Get a property on the type that is stored in the 
        // property string
        PropertyInfo prop = type.GetProperty(property);

        // Set the value of the given property on the given instance
        prop.SetValue(instance, value, null);

        // at this stage instance.Bar will equal to the value
        Console.WriteLine(((Foo)instance).Bar);
    }
}

If you had System.TypeLoad Exception, your class name is wrong.

To method Type.GetType you must enter assembly-qualified name . That is with the project name For example: GenerateClassDynamically_ConsoleApp1.Foo

If it is in another assembly jou must enter assembly name after comma (details on https://stackoverflow.com/a/3512351/1540350 ): Type.GetType("GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1");

Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null");
if (tp != null)
{
    object o = Activator.CreateInstance(tp);
    Control x = (Control)o;
    panel1.Controls.Add(x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM