c# 基本 用法

来源:互联网 发布:怎么修改淘宝上的地址 编辑:程序博客网 时间:2024/06/07 19:20

First  and FirstOrDefault 



int a;int b a.CompareTo(b);如果a大于等于b 返回>=0,反之小于0





String.PadLeft 方法

返回一个新字符串,该字符串通过在此实例中的字符左侧填充空格来达到指定的总长度,从而实现右对齐。

//C#构造函数 初始化器的使用
public class A
    {
        private int i = 0;
        public A()
        {
            i += 2;
            Debug.LogWarning("A(): "+ i);
        }
        public A(int a):this()
        {
            i += a;
            Debug.LogWarning("A(int a): " + i);
        }
        public A(int a, int b) : this(b)
        {
            i += a;
            Debug.LogWarning("A(int a, int b): " + i);
        }
        public int GetValue()
        {
            return i;
        }
    }

A a = new A(4, 6);
            Debug.LogWarning(a.GetValue());

打印的顺序是:
 A(): 2
A(int a): 8
A(int a, int b): 12
12

//复制出来一部分数据
public static List<T> deepCopy<T>(List<T> list)
    {
        List<T> list1 = new List<T>();
        if (list != null && list.Count > 0)
        {
            for (int l = 0; l < list.Count; l++)
            {
                list1.Add(Clone<T>(list[l]));
            }
        }
        return list1;
    }


    public static T Clone<T>(T RealObject)
    {
        using (Stream objectStream = new MemoryStream())
        {
            //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(objectStream, RealObject);
            objectStream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(objectStream);
        }
    }复制代码



public enum SkillType
        {
            JumpAttack = 0,
            FocoAttack,
            SwipeAttack,
            Skill1,
            Appear,
            SkillBegin = Skill1,
            Skill2,
            Skill3,
            Skill4,
            Skill5
        }


skill 1 和 skillBegin 都是3 Appear 是4 skill4 是6

public enum SkillType
        {
            JumpAttack = 0,
            FocoAttack,
            SwipeAttack,
            Skill1,
            SkillBegin = Skill1,
            Appear,
            Skill2,
            Skill3,
            Skill4,
            Skill5
        }


skill 1 和 skillBegin 都是3 Appear 是4 skill4 是7



(1)、C#语法中一个个问号(?)的运算符是指可以为 null 的类型。

 MSDN上面的解释:

在处理数据库和其他包含不可赋值的元素的数据类型时,将 null 赋值给数值类型布尔型以及日期类型的功能特别有用。例如,数据库中的布尔型字段可以存储值 true 或 false,或者,该字段也可以未定义。

 

 (2)、C#语法中两个问号(??)的运算符是指null 合并运算符,合并运算符为类型转换定义了一个预设值,以防可空类型的值为Null。

MSDN上面的解释:

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数(左边表达式);否则当左操作数为 null,返回右操作数(右边表达式)。 


C# Code:

int? x = null;//定义可空类型变量
int? y = x ?? 1000;//使用合并运算符,当变量x为null时,预设赋值1000

Console.WriteLine(y.ToString()); //1000

 

        /// <summary>
        /// Gets a single instance
        /// </summary>
        public static Log LogInstance
        {
              get

              {

                   return _log ?? (_log = new Log()); //如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
               }
        }




 1 #region
Enumberable First() or FirstOrDefault()
 2         /// <summary> 3         /// 返回序列中的第一个元素;如果序列中不包含任何元素,则返回默认值。  4         /// 如果 source 为空,则返回 default(TSource);否则返回 source 中的第一个元素。 5         /// ArgumentNullException      sourcevalue 为 null。 6         /// </summary> 7         public static void FunFirstOrDefault() 8         { 9             //FirstOrDefault()10             string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };11             // string[] names = { }; // string 类型的默认值是空12 13             int[] sexs = { 100, 229, 44, 3, 2, 1 };14             // int[] sexs = { };  // 因为int 类型的默认值是0. 所以当int[] 数组中没有任何元素时。default value is 0; 如果有元素,则返回第一个元素15 16             //原方法: public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);   // 扩展了IEnumerable<TSource>  接口17             //string namevalue = names.FirstOrDefault();  // string IEnumerable<string>.FirstOrDefault<string>();18             int sexvalue = sexs.FirstOrDefault(); // int IEnumerable<int>.FirstOrDefault<string>();19             //string namevalue = names.DefaultIfEmpty("QI").First();20             string namevalue = names.FirstOrDefault();21             Console.WriteLine("FirstOrDefault(): default(TSource) if source is empty; otherwise, the first element in source:{0}", namevalue);22 23 24         }25 26         /// <summary>27         /// 返回序列中的第一个元素。 28         /// 如果 source 中不包含任何元素,则 First<TSource>(IEnumerable<TSource>) 方法将引发异常29         /// ArgumentNullException      sourcevalue 为 null。30         //  InvalidOperationException  源序列为空。31         /// </summary>32         public static void FunFirst()33         {34             //First()35             string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };36             // string[] names = { };37 38             int[] sexs = { 100, 229, 44, 3, 2, 1 };39             //int[] sexs = { };40             int fsex = sexs.First();41             string fname = names.First(); // 如果序列中没有元素则会发生,InvalidOperationException 异常。 源序列为空。42 43             Console.WriteLine("First(): Returns the first element of a sequence : {0}", fname);44 45         }46         #endregion
复制代码

以上是我在本地验证的code.

需要注意的是:

 

这都是扩展了IEnumerable 这个接口。

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);

First 和 FirstOrDefault 最大的区别在于。 当集合(这个集合可以是:Arry,List,等等)中没有元素的时候。 First 会报异常 InvalidOperationException 源序列为空。
而 FirstOrDefault 则不会。


c#计时方法

  1. //秒表方法一:  
  2.        Stopwatch sw = new Stopwatch();  
  3.        sw.Start();  
  4.        for (int i = 0; i < 10000; i++)  
  5.        {  
  6.   
  7.        }  
  8.        sw.Stop();  
  9.        MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());  
  10.   
  11.        //当前时间减去开始时间方法二:  
  12.        DateTime begintime = DateTime.Now;  
  13.        for (int i = 0; i < 10000; i++)  
  14.        {  
  15.   
  16.        }  
  17.        TimeSpan ts = DateTime.Now.Subtract(begintime);  
  18.        MessageBox.Show(ts.TotalMilliseconds.ToString());  
一般md5加密,分为字符串加密和文件加密两种。这里说的加密只是一种不严谨的说法,实际并非加密,只是一种散列算法,其不可逆,即拿到一个md5值不能反向得到源字符串或源文件内容,

#region 1.获得md5值


        public static string GetMD5(string msg)
        {
            StringBuilder sb = new StringBuilder();


            using (MD5 md5=MD5.Create())
            {
                byte[] buffer = Encoding.UTF8.GetBytes(msg);
                byte[] newB = md5.ComputeHash(buffer);


                foreach (byte item in newB)
                {
                    sb.Append(item.ToString("x2"));
                }
            }


            return sb.ToString();
        }


        #endregion

#region 2获得一个文件的MD5


        public static string GetFileMD5(string filepath)
        {
            StringBuilder sb = new StringBuilder();
            using (MD5 md5=MD5.Create())
            {
                using (FileStream fs=File.OpenRead(filepath))
                {
                    byte[] newB = md5.ComputeHash(fs);
                    foreach (byte item in newB)
                    {
                        sb.Append(item.ToString("x2"));
                    }
                }
            }


            return sb.ToString();
        }


        #endregion

 C#MD5加密解密

using System.Security.Cryptography;
using    System.IO;  
using    System.Text; 

///MD5加密
  public string MD5Encrypt(string    pToEncrypt,  string    sKey)
    {  
     DESCryptoServiceProvider    des  =  new    DESCryptoServiceProvider();  
   byte[]    inputByteArray  =    Encoding.Default.GetBytes(pToEncrypt);  
     des.Key  =    ASCIIEncoding.ASCII.GetBytes(sKey);  
     des.IV  =    ASCIIEncoding.ASCII.GetBytes(sKey);  
     MemoryStream    ms  =  new    MemoryStream();  
     CryptoStream    cs  =  new    CryptoStream(ms,    des.CreateEncryptor(),CryptoStreamMode.Write);  
     cs.Write(inputByteArray,  0,    inputByteArray.Length);  
     cs.FlushFinalBlock();  
     StringBuilder    ret  =  new    StringBuilder();  
   foreach(byte    b  in    ms.ToArray())  
     {  
      ret.AppendFormat("{0:X2}",    b);  
     }  
     ret.ToString();  
   return    ret.ToString();  


    }

  ///MD5解密
  public string MD5Decrypt(string    pToDecrypt,  string    sKey)
    { 
     DESCryptoServiceProvider    des  =  new    DESCryptoServiceProvider();  

   byte[]    inputByteArray  =  new  byte[pToDecrypt.Length  /  2];  
   for(int    x  =  0;    x  <    pToDecrypt.Length  /  2;    x++)  
     {  
    int    i  =    (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));  
      inputByteArray[x]  =    (byte)i;  
     }  

     des.Key  =    ASCIIEncoding.ASCII.GetBytes(sKey);  
     des.IV  =    ASCIIEncoding.ASCII.GetBytes(sKey);  
     MemoryStream    ms  =  new    MemoryStream();  
     CryptoStream    cs  =  new    CryptoStream(ms,    des.CreateDecryptor(),CryptoStreamMode.Write);  
     cs.Write(inputByteArray,  0,    inputByteArray.Length);  
     cs.FlushFinalBlock();  

     StringBuilder    ret  =  new    StringBuilder();  
             
   return    System.Text.Encoding.Default.GetString(ms.ToArray());  
    }

-------------------------------------------------------------------------------

using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
class DES
{
// 创建Key
public string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
// 加密字符串
public string EncryptString(string sInputString, string sKey)
{
byte [] data = Encoding.UTF8.GetBytes(sInputString);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
// 解密字符串
public string DecryptString(string sInputString, string sKey)
{
string [] sInput = sInputString.Split("-".ToCharArray());
byte [] data = new byte[sInput.Length];
for(int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
}
class Test
{
static void Main()
{
DES des = new DES();
string key = des.GenerateKey();
string s0 = "中国软件 - csdn.net";
string s1 = des.EncryptString(s0, key);
string s2 = des.DecryptString(s1, key);
Console.WriteLine("原串: [{0}]", s0);
Console.WriteLine("加密: [{0}]", s1);
Console.WriteLine("解密: [{0}]", s2);
}
}
/* 程序输出:
原串: [中国软件 - csdn.net]
加密: [E8-30-D0-F2-2F-66-52-14-45-9A-DC-C5-85-E7-62-9B-AD-B7-82-CF-A8-0A-59-77]
解密: [中国软件 - csdn.net]
*/


从网页上提取用户邮箱为每个邮箱发送一封邮件


WebClient wc = new WebClient();
            string html = wc.DownloadString("http://laiba.tianya.cn/tribe/showArticle.jsp?groupId=93803&articleId=255105449041749990113803&curPageNo=1&h=p_1255011420000");
            string reg = "[a-zA-Z0-9_\\.]+@[a-zA-Z0-9_\\.]+\\.[a-zA-Z0-9_\\.]+";
            MatchCollection matches = Regex.Matches(html, reg);


            List<string> listEmail = new List<string>();
            foreach (Match mt in matches)
            {
                listEmail.Add(mt.Groups[0].Value);
            }


            //------------------以下是创建邮件和发送邮件的过程----------------------
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress("****@qq.com");
                mail.To.Add("*****@qq.com");
                foreach (string email in listEmail)
                {
                    mail.To.Add(email);
                }                
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Subject = "测试邮件";
                mail.BodyEncoding = Encoding.UTF8;
                mail.Body = "c#程序控制控!!!!!!!";


                //创建html的邮件内容
                AlternateView view = AlternateView.CreateAlternateViewFromString("文字在这里,也可以是<h1>html</h1>的代码<img src=\"cid:img001\" />", Encoding.UTF8, "text/html");
                LinkedResource lr = new LinkedResource(@"E:\图片\pics\雷锋.jpg");
                lr.ContentId = "img001";


                view.LinkedResources.Add(lr);
                mail.AlternateViews.Add(view);


                //为邮件添加附件
                Attachment at = new Attachment(@"D:\项目\chinatt315\members\qiyetupian\batianshengtai01.jpg");
                Attachment at1 = new Attachment(@"D:\项目\chinatt315\2011315hd\qytp\piyopiyo2.jpg");
                mail.Attachments.Add(at);
                mail.Attachments.Add(at1);




                SmtpClient smtp = new SmtpClient("pop.qq.com");
                smtp.Credentials = new NetworkCredential("用户名", "密码$");
                
                //为每个邮箱发送2封相同的邮件
                for (int i = 0; i < 2; i++)
                {
                    smtp.Send(mail);
                }                
                Console.WriteLine("发送成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送失败!"+ex.Message);
            }


            Console.ReadKey();

0 0
原创粉丝点击