可不可以根据一个字符串来对一个对像进行属性赋值?例如:    Demo1 有一个属性 P1
    Demo2 有一个属性 P2现在我要对过“P1”,“P2” 对这两个对象进行赋值。(假设类型是STRING型)
即不能通过 
Demo1.P1 = "xxx";
Demo2.P2 = "XXX";

解决方案 »

  1.   

    参考:
    public virtual void SetValue (
    Object obj,
    Object value,
    Object[] index
    )你先得到该属性的PropertyInfo,然后调用上面的这个方法去set它的值.比如:
    using System;
    using System.Reflection;class MyClass
    {
        private int myProperty;
        // Declare MyProperty.
        public int MyProperty
        {
            get
            {
                return myProperty;
            }
            set
            {
                myProperty=value;
            }
        }
    }
    public class MyTypeClass
    {
        public static void Main(string[] args)
        {
            try
            {
                // Get the Type object corresponding to MyClass.
                MyClass c = new MyClass();
                c.MyProperty = 1;
                Type myType=typeof(c);       
                // Get the PropertyInfo object by passing the property name.
                PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
                // Display the property name.
                Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name);
                myPropInfo.SetValue(c,2,null)//将属性MyProperty设置为2
            }
            catch(NullReferenceException e)
            {
                Console.WriteLine("The property does not exist in MyClass." + e.Message);
            }
        }
    }