C#创建类的实例并按名称在字符串中设置属性 [英] C# creating instance of class and set properties by name in string

查看:101
本文介绍了C#创建类的实例并按名称在字符串中设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我想按名称创建类的实例。
我找到了 Activator.CreateInstance http://msdn.microsoft.com/zh-cn/library/d133hta4.aspx ,它工作正常,我发现了这一点:$ b​​ $ b 也通过反射使用字符串值设置属性

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 ?

推荐答案

您可以使用反射:

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);
    }
}

这篇关于C#创建类的实例并按名称在字符串中设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆