1. 程式人生 > >C#返回object物件的指定屬性

C#返回object物件的指定屬性

以object型別的物件返回其Shape屬性為例。

        /// <summary>
        /// 返回Object物件的指定屬性
        /// </summary>
        /// <param name="obj">傳入的物件</param>
        /// <returns>返回的屬性</returns>
        private GeoJSON.Net.Geometry.Point GetShape(object obj)
        {
            System.Reflection.PropertyInfo a = null;
            foreach (System.Reflection.PropertyInfo pi in obj.GetType().GetProperties())
            {
                if (pi.CanWrite)
                {
                    if (0 == string.Compare("Shape", pi.Name, true))
                    {
                        a = pi;
                        break;
                    }
                }
            }
            if (null == a)
            {
                return null;
            }
            return a.GetValue(obj) as GeoJSON.Net.Geometry.Point;
        }