C# 小记
2010-07-26 21:32 音乐让我说 阅读(491) 评论(0) 收藏 举报- 关于显式实现接口:
public class Color { public static readonly Color Black = new Color(0, 0, 0); public static readonly Color White = new Color(255, 255, 255); public static readonly Color Red = new Color(255, 0, 0); public static readonly Color Green = new Color(0, 255, 0); public static readonly Color Blue = new Color(0, 0, 255); private byte r, g, b; public Color(byte r, byte g, byte b) { this.r = r; this.g = g; this.b = b; } } public class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } public class Point3D: Point { public int z; public Point3D(int x, int y, int z): base(x, y) { this.z = z; } } 对于显示接口实现,如: public class EditBox: IControl, IDataBound { void IControl.Paint() {...} void IDataBound.Bind(Binder b) {...} } 则调用的时候,必须这样: EditBox editBox = new EditBox(); editBox.Paint(); // Error, no such method IControl control = editBox; control.Paint(); // Ok
- C#基本数据类型的范围:
sbyte 8位 -128~127 System.SByte byte 8位 0~255 System.Byte short 16位 -32768~32767 System.Int16 ushort 16位 0~65535 System.UInt16 int 32位 -2147483648~2147483 647 System.Int32 uint 32位 0~4294967295 System.Int32 long 64位 -9223372036854775808~9223372036854775807 System.Int64 ulong 64位 0~18 446 744 073 709 551 615 System.Int64
-
HttpException 类:描述在处理Http 请求期间发生的异常。
- && 表示短路,如果左侧为false,则不计算右边的值,而& 左右两边都要计算
- int i = 16;int j = i << 3;Console.WriteLine(j);上面的结果为:128。即16乘以2的3次方,以此类推int j = i << 8 即16乘以2的8次方
- int i = 32;int j = i >> 3;Console.WriteLine(j);上面的结果为:4。即32除以2的3次方,以此类推int j = i << 8 即16除以2的8次方
- C#根据一个包含了xml数据的字符串来操作:
string userIdXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<users_getID_response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://nt.discuz.net/api/\">130807</users_getID_response>"; System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(userIdXML); System.Xml.XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("users_getID_response"); Console.WriteLine(xmlNodeList[0].InnerText); Console.ReadKey();
- 最简单的MD5加密,加密成16位密码,但加密成32位的密码(32位密码长度比16位长),因为32位的密码可以转换为16位,而16位则不能转为32位:
/// <summary> /// MD5加密 /// </summary> /// <param name="Code">需要加密的值</param> /// <returns>以加密的值</returns> protected string CreateMD5(string Code) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Code, "MD5").ToLower().Substring(8, 16); }
- int 的最大值是:2147483648 = 2*1024*1024*1024 = 2GB
- 关于数组的练习:
static void Main(string[] args) { int[,] nums1 = { {1,2,3},{4,5,6} }; //声明一个3列,2行的多维数组 Console.WriteLine(nums1.Length); //结果为6 Console.WriteLine(nums1[0,2]); //结果为3 int[][] num2 = { new int[] { 1,2,3,4,5 }, new int[] { 2 }, new int[] { 4,5 }, new int[] { 2,3,9,5 } }; //声明一个元素类型为Int 数组的交错数组 Console.WriteLine(num2.Length); //结果为4 Console.WriteLine(num2[3][2]); //结果为9 int[] num3; //除非声明数组后,马上初始化,否则,必须用 new int[3] num3 = new int[3] { 13, 16, 19 }; // 错误写法: num3 = { 13,16,19 }; 定义好数组后在初始化数值时需要new关键字。 //错误:int[] nums=new int[3]{}; //正确:int[] nums=new int[3]{1,2,3}; 初始化变量时如果指定了数组大小必须初始化数据,同时初始化的数据数量和指定的数组长度必须一样。 string script = @" <script type='text/javascript'> alert('Hello World'); </script> "; Console.WriteLine(script); char a = 'a'; //97 char f = 'f'; //102 Console.WriteLine("f-a=" + (f - a)); //结果为5 }
- 关于“??”操作符:
string name = null; Console.WriteLine("姓名:" + name); //NULL Console.WriteLine("姓名:" + (name ?? (name = "张三"))); //语义:name 为空吗?如果为空,则给name赋值“张三”并且返回“张三”。最后打印:“姓名:张三” Console.WriteLine("姓名:" + name); //张三
- 在C#中得到一个字符串的MD5值
//代码来自:http://www.cnblogs.com/fish-li/archive/2012/02/12/2348395.html public class AjaxDemo { [Action] public string GetMd5(string input) { if( input == null ) input = string.Empty; byte[] bb = (new MD5CryptoServiceProvider()).ComputeHash(Encoding.Default.GetBytes(input)); return BitConverter.ToString(bb).Replace("-", "").ToLower(); } }
- 集合扩展类:
/// <summary> /// 集合扩展类 /// </summary> public static class CollectionExtendsions { /// <summary> /// 将字典集合转换为动态字典集合 /// </summary> /// <typeparam name="TKey">字典的 Key</typeparam> /// <typeparam name="TValue">字典的 Value</typeparam> /// <param name="source">源字典</param> /// <returns></returns> public static Dictionary<dynamic, dynamic> Cast<TKey, TValue>(this Dictionary<TKey, TValue> source) { if (source == null) { throw new ArgumentNullException("source"); } Dictionary<dynamic, dynamic> result = new Dictionary<dynamic, dynamic>(); foreach (var item in source) { result.Add(item.Key, item.Value); } return result; } }
- UrlHelper
public static class UrlHelper { // Methods public static Uri Combine(this Uri uri, string path) { string combined; string url = uri.ToString(); if (url.EndsWith("/") && path.StartsWith("/")) combined = url + path.Substring(1); else combined = url + path; return new Uri(combined); } }
- 修改 C# 中的 Resource(资源)文件生成的代码的默认可见性为 public:右键你的 .resx 文件,在属性框中将 Custom Tool 改为 PublicResXFileCodeGenerator
- C# 产生多个相同的字符
static void Main(string[] args) { string word = new string('a', 100); Console.WriteLine(word); }
- 匹配 Http 链接的正则表达式:
http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
- C# 注释某个类或方法,换行显示文字。
/// <summary> /// <para>拆分一个字符串行。如:a=1;b=2;c=3;d=4;</para> /// <para>此时可以调用: SplitString("a=1;b=2;c=3;d=4;", ';', '=');</para> /// <para>说明:对于空字符串,方法也会返回一个空的列表。</para> /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
- Throw 和 Throw ex 的区别:堆栈信息的起始点不同,throw ex 会将到现在为止的所有信息清空,而 throw 则不会,但推荐进一步包装的异常,比如:throw new Exception("经过进一步包装的异常", ex);
测试地址:http://www.cnblogs.com/JerryTian/archive/2012/09/24/2699459.html - 在 C# 中,判断某个方法是否是直接或间接的继承至某个类。
比如:HomeController 中有一个 Index 方法,判断这个 Index 方法是否是继承至 Controller。 MethodInfo methodInfo = ?; methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(Controller))
- 用 base64 码显示图片
<div> <p> 下面是图片 </p> <p> <img alt="sample" src="@Url.Content("~/Content/testImage.jpg")"/> </p> </div> @{ string base64Data = Convert.ToBase64String(File.ReadAllBytes(Server.MapPath("~/Content/testImage.jpg"))); } <div> <p> 下面是图片编码后 </p> <p> <img alt="sample" src="data:image/png;base64,@base64Data"/> </p> </div>
- 检查目标目录是否以目录分割字符结束如果不是则添加之
// 检查目标目录是否以目录分割字符结束如果不是则添加之 if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) { aimPath += Path.DirectorySeparatorChar; }
- C# 中复制文件夹下所有的子文件夹、文件到另一个目录
/// <summary> /// 复制目录下的所有文件夹、子文件夹和文件到另一个目录。 /// </summary> /// <param name="srcPath">源目录,比如:D:\sourceDir。备注:只复制 D:\sourceDir 下的所有</param> /// <param name="aimPath">目标目录,比如:D:\destDir。</param> public static void CopyDir(string srcPath, string aimPath) { // 检查目标目录是否以目录分割字符结束如果不是则添加之 if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) { aimPath += Path.DirectorySeparatorChar; } // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath); // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 // string[] fileList = Directory.GetFiles(srcPath); string[] fileList = Directory.GetFileSystemEntries(srcPath); // 遍历所有的文件和目录 foreach (string file in fileList) { // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 if (Directory.Exists(file)) CopyDir(file, aimPath + Path.GetFileName(file)); // 否则直接Copy文件 else File.Copy(file, aimPath + Path.GetFileName(file), true); } }
-
// Make sure we have permission to read the XML data source and // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, @"C:\users.xml"); permission.Demand();
- C# 操作符重载的示例A:
public static CPQuery operator +(CPQuery query, string s) { query.AddSqlText(s); return query; }
- 关于判断类型
int obj = 10; IConvertible conv = obj as IConvertible; if (conv != null) { switch (conv.GetTypeCode()) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DBNull: break; case TypeCode.DateTime: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: break; case TypeCode.Int32: break; default: break; } } else { //处理其他类型 }
- 下面的代码是让内存溢出:
- System_linq_Dynamic 下载:https://files.cnblogs.com/Music/System_linq_Dynamic_Ref_Blog.zip
- 如图:
- 单元测试练习:
- 生成静态页原理
/// <summary> /// 生成静态 /// </summary> /// <param name="m">分,默认为3分钟</param> /// <returns></returns> public ContentResult Html(int? m) { try { int Minute = 3; if (m!=null) Minute = (int)m; string FileName = Server.MapPath("/")+"index.html"; FileInfo fi = new FileInfo(FileName); //修改时间大于3 重新生成 if ((DateTime.Now - fi.LastWriteTime).Minutes >= Minute) { SiteCache.Remove(SiteCacheDataModels.SiteIndexKey); string PageUrl =Request.Url.ToString().Replace(Request.RawUrl, "/")+"Default/Index"; //Response.Write(PageUrl); WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; Byte[] pageData = wc.DownloadData(PageUrl); using (StreamWriter streamWriter = fi.CreateText()) { streamWriter.Write(System.Text.Encoding.UTF8.GetString(pageData)); streamWriter.Flush(); } Response.Write("Success"); } } catch (Exception ex) { Response.Write("<div style=\"display:none;\">" + ex.Message + "</div>"); } return null; }
- 谢谢浏览...
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。