快速开发平台提供一组实体操作方法--缓存表达式树和枚举

快速开发平台为大家提供一组软件类实体操作方法-- 缓存表达式树、反射赋值和枚举等

快速开发平台实体操作缓存表达式树和枚举

附上源码:包含软件类实体操作方法-- 缓存表达式树、反射赋值和枚举等。 

        private static AspNetHostingPermissionLevel? _trustLevel = null;
        /// <summary>
        /// Finds the trust level of the running application
        /// </summary>
        /// <returns>The current trust level.</returns>
        public static AspNetHostingPermissionLevel GetTrustLevel()
        {
            if (!_trustLevel.HasValue)
            {
                //set minimum
                _trustLevel = AspNetHostingPermissionLevel.None;
                //determine maximum
                foreach (AspNetHostingPermissionLevel trustLevel in
                        new AspNetHostingPermissionLevel[] {
                                AspNetHostingPermissionLevel.Unrestricted,
                                AspNetHostingPermissionLevel.High,
                                AspNetHostingPermissionLevel.Medium,
                                AspNetHostingPermissionLevel.Low,
                                AspNetHostingPermissionLevel.Minimal 
                            })
                {
                    try
                    {
                        new AspNetHostingPermission(trustLevel).Demand();
                        _trustLevel = trustLevel;
                        break; //we've set the highest permission we can
                    }
                    catch (System.Security.SecurityException)
                    {
                        continue;
                    }
                }
            }
            return _trustLevel.Value;
        }
        /// <summary>
        /// 反射赋值
        /// </summary>
        /// <param name="instance">The object whose property to set.</param>
        /// <param name="propertyName">The name of the property to set.</param>
        /// <param name="value">The value to set the property to.</param>
        public static void SetProperty(object instance, string propertyName, object value)
        {
            if (instance == null) throw new ArgumentNullException("instance");
            if (propertyName == null) throw new ArgumentNullException("propertyName");
            Type instanceType = instance.GetType();
            PropertyInfo pi = instanceType.GetProperty(propertyName);
            if (pi == null)
                throw new Exception(string.Format("No property '{0}' found on the instance of type '{1}'.", propertyName, instanceType));
            if (!pi.CanWrite)
                throw new Exception(string.Format("The property '{0}' on the instance of type '{1}' does not have a setter.", propertyName, instanceType));
            if (value != null && !value.GetType().IsAssignableFrom(pi.PropertyType))
                value = To(value, pi.PropertyType);
            pi.SetValue(instance, value, new object[0]);
        }
        //枚举操作 public static TypeConverter GetCustomTypeConverter(Type type)
        {
            //we can't use the following code in order to register our custom type descriptors
            //TypeDescriptor.AddAttributes(typeof(List<int>), new TypeConverterAttribute(typeof(GenericListTypeConverter<int>)));
            //so we do it manually here
            if (type == typeof(List<int>))
                return new GenericListTypeConverter<int>();
            if (type == typeof(List<decimal>))
                return new GenericListTypeConverter<decimal>();
            if (type == typeof(List<string>))
                return new GenericListTypeConverter<string>();
            return TypeDescriptor.GetConverter(type);
        }
        /// <summary>
        /// Converts a value to a destination type.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="destinationType">The type to convert the value to.</param>
        /// <returns>The converted value.</returns>
        public static object To(object value, Type destinationType)
        {
            return To(value, destinationType, CultureInfo.InvariantCulture);
        }
        /// <summary>
        /// Converts a value to a destination type.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="destinationType">The type to convert the value to.</param>
        /// <param name="culture">Culture</param>
        /// <returns>The converted value.</returns>
        public static object To(object value, Type destinationType, CultureInfo culture)
        {
            if (value != null)
            {
                var sourceType = value.GetType();
                TypeConverter destinationConverter = GetCustomTypeConverter(destinationType);
                TypeConverter sourceConverter = GetCustomTypeConverter(sourceType);
                if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
                    return destinationConverter.ConvertFrom(null, culture, value);
                if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
                    return sourceConverter.ConvertTo(null, culture, value, destinationType);
                if (destinationType.IsEnum && value is int)
                    return Enum.ToObject(destinationType, (int)value);
                if (!destinationType.IsAssignableFrom(value.GetType()))
                    return Convert.ChangeType(value, destinationType, culture);
            }
            return value;
        }
        /// <summary>
        /// Converts a value to a destination type.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <typeparam name="T">The type to convert the value to.</typeparam>
        /// <returns>The converted value.</returns>
        public static T To<T>(object value)
        {
            //return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
            return (T)To(value, typeof(T));
        }
        /// <summary>
        /// Convert enum for front-end
        /// </summary>
        /// <param name="str">Input string</param>
        /// <returns>Converted string</returns>
        public static string ConvertEnum(string str)
        {
            string result = string.Empty;
            char[] letters = str.ToCharArray();
            foreach (char c in letters)
                if (c.ToString() != c.ToString().ToLower())
                    result += " " + c.ToString();
                else
                    result += c.ToString();
            return result;
        }
        /// <summary>
        /// Set Telerik (Kendo UI) culture
        /// </summary>
        public static void SetTelerikCulture()
        {
            //little hack here
            //always set culture to 'en-US' (Kendo UI has a bug related to editing decimal values in other cultures)
            var culture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
        //缓存表达式树
        private static Dictionary<string, object> objCache = new Dictionary<string, object>();
 /// <summary>
        /// 使用表达式树为两个对象的相同属性赋值
        /// </summary>
        /// <typeparam name="TIn">源对象</typeparam>
        /// <typeparam name="TOut">目标对象</typeparam>
        /// <param name="tIn">源实例</param>
        /// <returns>目标实例,返回新实例</returns>
        public static TOut ObjCopyByExpressionTree<TIn, TOut>(TIn tIn)
        {
            string key = string.Format("Key_{0}_To_{1}", typeof(TIn).FullName, typeof(TOut).FullName);
            if (!objCache.ContainsKey(key))
            {
                //表示一个命名的参数表达式
                //创建一个 System.Linq.Expressions.ParameterExpression 节点,该节点可用于标识表达式树中的参数或变量
                //   type:
                //     参数或变量的类型。
                //
                //   name:
                //     仅用于调试或打印目的的参数或变量的名称
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "parameter");
                //提供表示绑定的类派生自的基类,这些绑定用于对新创建对象的成员进行初始化
                List<MemberBinding> memberBindingList = new List<MemberBinding>();
                foreach (var item in typeof(TOut).GetProperties())
                {
                    try
                    {
                        //表示访问字段或属性
                        //   expression:
                        //     要将 System.Linq.Expressions.Expression 属性设置为与其相等的 System.Linq.Expressions.MemberExpression.Expression。
                        //     对于静态属性,这可以为 null。
                        //
                        //   property:
                        //     要将 System.Reflection.PropertyInfo 属性设置为与其相等的 System.Linq.Expressions.MemberExpression.Member。
                        MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                        //提供表示绑定的类派生自的基类,这些绑定用于对新创建对象的成员进行初始化。
                        MemberBinding memberBinding = Expression.Bind(item, property);
                        memberBindingList.Add(memberBinding);
                    }
                    catch { }
                };
                //表示调用构造函数并初始化新对象的一个或多个成员。
                MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
                //将强类型化的 Lambda 表达式表示为表达式树形式的数据结构
                Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
                //封装一个方法,该方法具有一个参数,且返回由 TResult 参数指定的类型的值
                //编译表达式树由描述为可执行代码的 lambda 表达式,并生成一个委托,表示 lambda 表达式
                Func<TIn, TOut> func = lambda.Compile();
                objCache[key] = func;
            }
            return ((Func<TIn, TOut>)objCache[key])(tIn);
        }

网站&系统开发技术学习交流群:463167176

本站文章除注明转载外,均为本站原创或翻译,欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,共创和谐网络环境。
转载请注明:文章转载自:软件开发框架 » 快速开发平台提供一组实体操作方法--缓存表达式树和枚举
本文标题:快速开发平台提供一组实体操作方法--缓存表达式树和枚举
本文地址:https://www.hocode.com/OrgTec/Back/0035.html

相关文章: Web框架UI系列—平台四种组件类控件一

电话
电话 18718672256

扫一扫
二维码