首页 > 代码库 > C#帮助类

C#帮助类

1、集合操作

        // <summary>        /// 判断一个集合是否包含某个值        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="list"></param>        /// <param name="value"></param>        /// <returns>返回索引值</returns>        public static int IsContainValue<T>(IEnumerable<T> list, T value)        {            return list.ToList<T>().FindIndex(i => i.Equals(value));        }

2、反射

        /// <summary>        ///  实例化反射对象        /// </summary>        /// <param name="t">如果类型为null,就根据对象获取类型</param>        /// <param name="obj">如果对象为null,就根据类型实例化对象</param>        static void JudgeType(ref Type t, ref object obj, ref BindingFlags flags, bool isPublic, bool isStatic)        {            if (t != null)            {                obj = Activator.CreateInstance(t);            }            else            {                t = obj.GetType();            }            flags = (isStatic ? BindingFlags.Static : BindingFlags.Instance) | (isPublic ? BindingFlags.Public : BindingFlags.NonPublic);        }        /// <summary>        /// 获取对象的属性或者字段的值        /// </summary>        /// <param name="t">如果类型为null,就根据对象获取类型</param>        /// <param name="obj">如果对象为null,就根据类型实例化对象</param>        /// <param name="name">属性或者字段的名称</param>        /// <param name="isPublic">是否是public修饰符修饰的</param>        /// <param name="isStatic">是否是静态的</param>        /// <returns>返回字段或者属性的值</returns>        public static object GetFieldOrProperty(Type t, object obj, string name, bool isPublic, bool isStatic)        {            BindingFlags flags = BindingFlags.Default;            JudgeType(ref t, ref  obj, ref flags, isPublic, isStatic);            FieldInfo fieldInfo = t.GetField(name, flags);            if (fieldInfo == null)            {                PropertyInfo propertyInfo = t.GetProperty(name, flags);                if (propertyInfo != null)                {                    return propertyInfo.GetValue(obj, null);                }                return null;            }            return fieldInfo.GetValue(obj);        }        /// <summary>        /// 反射执行对象的方法        /// </summary>        /// <param name="t">如果类型为null,就根据对象获取类型</param>        /// <param name="obj">如果对象为null,就根据类型实例化对象</param>        /// <param name="methodName">方法名称</param>        /// <param name="parameters">方法参数</param>        /// <param name="isPublic">是否是public修饰符修饰的</param>        /// <param name="isStatic">是否是静态的</param>        public static void ExecuteMethod(Type t, object obj, string methodName, object[] parameters, bool isPublic, bool isStatic)        {            BindingFlags flags = BindingFlags.Default;            JudgeType(ref t, ref obj, ref flags, isPublic, isStatic);            MethodInfo methodInfo = t.GetMethod(methodName, flags);            if (methodInfo != null)            {                methodInfo.Invoke(obj, parameters);            }        }        /// <summary>        /// 得到属性或者字段或者方法的特性        /// </summary>        /// <param name="t">如果类型为null,就根据对象获取类型</param>        /// <param name="obj">如果对象为null,就根据类型实例化对象</param>        /// <param name="name">名称</param>        /// <param name="isPublic">是否是public修饰符修饰的</param>        /// <param name="isStatic">是否是静态的</param>        /// <returns></returns>        public static object[] GetCustomAttributes(Type t, object obj, string name, bool isPublic, bool isStatic)        {            BindingFlags flags = BindingFlags.Default;            JudgeType(ref t, ref obj, ref flags, isPublic, isStatic);            MethodInfo methodInfo = t.GetMethod(name, flags);            if (methodInfo != null)            {                return methodInfo.GetCustomAttributes(false);            }            else            {                FieldInfo fieldInfo = t.GetField(name, flags);                if (fieldInfo != null)                {                    return fieldInfo.GetCustomAttributes(false);                }                else                {                    PropertyInfo propertyInfo = t.GetProperty(name, flags);                    if (propertyInfo != null)                    {                        return propertyInfo.GetCustomAttributes(false);                    }                    return null;                }            }        }        /// <summary>        /// 加载程序集,并实例化对象        /// </summary>        /// <param name="dllPath">程序集路径(绝对路径)</param>        /// <param name="index">为-1,表示要实例化所有对象,不为-1,表示要实例化索引为index的对象</param>        /// <param name="objList">输出实例化的对象</param>        /// <returns>返回所有类型</returns>        public static Type[] GetTypes(string dllPath, int index, ref List<object> objList)        {            objList = new List<object>();            Type[] t;            object obj;            Assembly assembly = Assembly.LoadFile(dllPath);            t = assembly.GetTypes();            if (index == -1)            {                foreach (var item in t)                {                    obj = Activator.CreateInstance(item);                    objList.Add(obj);                }            }            else            {                obj = Activator.CreateInstance(t[index]);                objList.Add(obj);            }            return t;        }

3、序列化

        // JavaScriptSerializer在net3.5中已被标记“过时”,使用这个类,必须引用System.Web.Extensions.dll        // 新的序列化类“DataContractJsonSerializer”,使用DataContract和DataMember特性来分别标记你要序列化的对象和成员        // 如果不想序列化某个成员,就标记为 [IgnoreDataMember]        // 你可以在DataMember属性里用"Name"参数指定名称,例子如下:        // [DataMember(Name = "First")]         // public string FirstName { get; set; }         // 序列化后的结果:{"First":"Chris","LastName":"Pietschmann"}         /// <summary>        /// 序列化,需要引用System.Runtime.Serialization和System.ServiceModel.Web        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="obj"></param>        /// <returns></returns>        public static string Serialize<T>(T obj)        {            using (MemoryStream stream = new MemoryStream())            {                string result = string.Empty;                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());                serializer.WriteObject(stream, obj);                result = Convert.ToBase64String(stream.ToArray(), Base64FormattingOptions.None);                return result;            }        }        /// <summary>        /// 反序列化        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="str"></param>        /// <returns></returns>        public static T Deserialize<T>(string str)        {            //T obj = Activator.CreateInstance<T>();            using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(str)))            {                DataContractJsonSerializer deserialize = new DataContractJsonSerializer(typeof(T));                var obj = (T)deserialize.ReadObject(stream);                return obj;            }        }

4、网页

        /// <summary>        /// 获取网页源文件        /// </summary>        /// <param name="url"></param>        /// <returns></returns>        public static string GetWebContent(string url)        {            System.Net.WebClient wc = new System.Net.WebClient();            wc.Credentials = System.Net.CredentialCache.DefaultCredentials;            return wc.DownloadString(url);        }        /// <summary>        ///  向网页发送Post或者Get请求        /// </summary>        private static CookieContainer cookie = new CookieContainer();// 主要是设置session值        public static string WebRequest(string url, bool isPost, IDictionary<string, string> parames)        {            HttpWebRequest webRequest = null;            string param = string.Empty;            foreach (var item in parames.Keys)            {                param += item + "=" + parames[item] + "&";            }            param.TrimEnd(&);            if (!isPost)                url += "?" + param;            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;            webRequest.Method = isPost ? "Post" : "Get";            webRequest.KeepAlive = true;            webRequest.CookieContainer = cookie;            webRequest.Timeout = 1000 * 60;            webRequest.ContentType = "application/x-www-form-urlencoded";            if (isPost)            {                byte[] bs = Encoding.UTF8.GetBytes(param);                webRequest.ContentLength = bs.Length;                using (Stream requestWriter = webRequest.GetRequestStream())                {                    requestWriter.Write(bs, 0, bs.Length);                }            }            WebResponse webResponse = webRequest.GetResponse();            //string cookieheader = webRequest.CookieContainer.GetCookieHeader(new Uri(url));            //cookie.SetCookies(new Uri(url), cookieheader);            string responseData = http://www.mamicode.com/string.Empty;            using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()))            {                responseData = responseReader.ReadToEnd();            }            return responseData;        }

 

C#帮助类