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; } }
另一个序列化方式为Json.NET
性能比较如下:
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 bool MyWebRequest(string url, bool isPost, IDictionary<string, string> parames, out string serverMsg) { try { string param = string.Empty; if (parames != null) { foreach (var item in parames.Keys) { param += item + "=" + parames[item] + "&"; } } param.TrimEnd('&'); if (!isPost) { url += "?" + param; } HttpWebRequest webRequest = 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); } } using (WebResponse webResponse = webRequest.GetResponse()) { //string cookieheader = webRequest.CookieContainer.GetCookieHeader(new Uri(url)); //cookie.SetCookies(new Uri(url), cookieheader); using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream())) { serverMsg = responseReader.ReadToEnd(); return true; } } } catch (Exception ex) { serverMsg = ex.Message; return false; } } //对应的服务端处理 public class Main : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpRequest hr = context.Request; //没必要区分是post还是get方式了,直接可以获取相对应的值了 string name = hr["name"]; //get方式获取值 string getName = hr.QueryString["name"]; //post方式获取值 string postName = hr.Form["name"]; context.Response.ContentType = "text/plain"; context.Response.Write("姓名:" + name + " = " + getName + " = " + postName); } public bool IsReusable { get { return false; } } }
/// <summary> /// json数据的Post请求 /// </summary> /// <param name="url">请求的地址</param> /// <param name="data">请求的jason参数</param> /// <param name="msg">服务器返回的消息或者异常信息</param> /// <returns>是否执行成功</returns> public static bool JsonPost(string url, string data, out string msg) { try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8)) { writer.Write(data); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { msg = reader.ReadToEnd(); return true; } } } } catch (Exception exception) { msg = exception.Message; return false; } } //对应的服务端处理 public class Main : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpRequest hr = context.Request; string result = string.Empty; using (Stream stream = hr.InputStream) { using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } } //此处对result进行json反序列化即可 context.Response.ContentType = "text/plain"; context.Response.Write("客户端发送的整体内容:" + result); } public bool IsReusable { get { return false; } } }
/// <summary> /// 上传文件到服务器 /// </summary> /// <param name="url">请求的服务器地址</param> /// <param name="uploadFile">要上传的文件本地路径</param> /// <param name="msg">服务器返回的消息或者异常信息</param> /// <returns>是否执行成功</returns> public static bool UploadFile(string url, string uploadFile, out string msg) { msg = string.Empty; try { using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 30, 0); using (FileStream stream = File.OpenRead(uploadFile)) { StreamContent content2 = new StreamContent(stream); using (MultipartFormDataContent content = new MultipartFormDataContent()) { content.Add(content2, "file", Path.GetFileName(uploadFile)); HttpResponseMessage result = client.PostAsync(url, content).Result; msg = result.Content.ReadAsStringAsync().Result; if (result.StatusCode.ToString() == "OK") { return true; } } } } } catch (Exception ex) { msg = ex.Message; } return false; } //对应的服务端处理 public class Main : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpRequest hr = context.Request; HttpFileCollection hfc = hr.Files; IList<HttpPostedFile> list = hfc.GetMultiple("file"); for (int i = 0; i < list.Count; i++) { HttpPostedFile ff = list[i];
//或者直接这样保存:ff.SaveAs("F:\\" + ff.FileName); using (Stream stream = ff.InputStream) { using (FileStream fs = File.OpenWrite("C:\\infoOver.txt")) { byte[] b = new byte[1024 * 1024 * 2]; int readlength = 0; while ((readlength = stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, readlength); } } } } context.Response.ContentType = "text/plain"; context.Response.Write("文件保存成功"); } public bool IsReusable { get { return false; } } }