代码改变世界

C# 中 动态获得或设置一个对象的值

2012-08-04 18:04  音乐让我说  阅读(2040)  评论(1编辑  收藏  举报

直接贴代码了:

    class Student
    {
        public int StuId { get; set; }
        public string StuName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new { Id = 18, Name = "bruce", DateOfBirth = new DateTime(1985,8,8), RandomNum = Guid.NewGuid() };

            TestGetPropertyValue(person);

            TestSetPropertyValue(new Student { StuId = 1, StuName = "Jacky" });
        }

        static void TestGetPropertyValue(object obj)
        {
            Console.WriteLine("以下是从一个对象中获取的信息:\n");

            int id = obj.GetPropertyValue<int>("Id", 6);
            Console.WriteLine("获取成功,Id: " + id);

            int id2 = obj.GetPropertyValue<int>("Id2", 7);
            Console.WriteLine("获取失败,返回默认的 Id2: " + id2);

            string name = obj.GetPropertyValue<string>("Name", "default Name");
            Console.WriteLine("获取成功,Name: " + name);

            DateTime dateOfBirth = obj.GetPropertyValue<DateTime>("DateOfBirth", new DateTime(2000,1,1));
            Console.WriteLine("获取成功,DateOfBirth: " + dateOfBirth);

            Guid randomNum = obj.GetPropertyValue<Guid>("RandomNum", Guid.Empty);
            Console.WriteLine("获取成功,RandomNum: " + randomNum);

            Console.WriteLine("\n获取完毕!\n\n");
            
        }

        static void TestSetPropertyValue(object obj)
        {
            string stuName = obj.GetPropertyValue<string>("StuName", "default StuName");
            Console.WriteLine("获取成功,StuName: " + stuName);

            obj.SetPropertyValue("StuName", "bruce liu");

            stuName = obj.GetPropertyValue<string>("StuName", "default bruce liu .");
            Console.WriteLine("动态设置后,StuName: " + stuName);

            Console.WriteLine("\n设置完毕!\n\n");
        }
    }

    public static class ObjectExtensions
    {

        /// <summary>
        /// 利用反射,动态获取一个 Property 的值(一般用于获得匿名类型的实例的值)
        /// </summary>
        /// <typeparam name="T">期望返回的类型</typeparam>
        /// <param name="obj">要获得的对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>是否成功,如果成功,则返回等效的值,否则返回默认值</returns>
        public static bool GetPropertyValue<T>(this object obj, string propertyName, out T returnValue)
        {
            Type type = obj.GetType();
            PropertyInfo property = type.GetProperty(propertyName);

            if (property == null)
            {
                returnValue = default(T);
                return false;
            }
            object value = property.GetValue(obj, null);
            if( value is T )
            {
                returnValue = (T)value;
                return true;
            }
            else
            {
                returnValue = default(T);
                return false;
            }
        }

        /// <summary>
        /// 利用反射,动态获取一个 Property 的值(一般用于获得匿名类型的实例的值)
        /// </summary>
        /// <typeparam name="T">期望返回的类型</typeparam>
        /// <param name="obj">要获得的对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>是否成功,如果成功,则返回等效的值,否则返回默认值</returns>
        public static T GetPropertyValue<T>(this object obj, string propertyName, T defaultValue)
        {
            T returnValue;
            return GetPropertyValue<T>(obj, propertyName, out returnValue) ? returnValue : defaultValue;
        }

        /// <summary>
        /// 利用反射,动态设置一个 Property 的值(一般用于设置具有 public setter 类型的实例的值)
        /// </summary>
        /// <param name="obj">要设置的对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="value">要设置的值</param>
        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
            Type type = obj.GetType();
            PropertyInfo property = type.GetProperty(propertyName);

            if (property != null)
            {
                property.SetValue(obj, value, null);
            }
        }
    }

 

运行截图:

 

也许你还会喜欢:代码练习在 C# 中得到一个 object (包含匿名对象)的属性和属性值

谢谢浏览!