C# How To系列

C# How To系列

1.实例化一个类
using System;
namespace Csharp_how_to
{
    class Program
    {
        static void Main(string[] args)
        {
            // method 1
            Student stu1 = new Student();
            stu1.Name = "tom";
            stu1.Id = 100;

            // method 2
            Student stu2 = new Student
            {
                Name = "jhon",
                Id = 99,
            };

            // method 3
            Student stu3 = new Student("james", 101);

            Console.WriteLine(stu1.ToString());
            Console.WriteLine(stu2.ToString());
            Console.WriteLine(stu3.ToString());

            Console.ReadKey();
        }
    }

    class Student
    {
        public string Name { get; set; }
        public int Id { get; set; }

        // no param constructor
        public Student()
        {

        }
        // two param constrcutor
        public Student(string name, int id)
        {
            this.Name = name;
            this.Id = id;
        }


        public override string ToString()
        {
            return "Name:" + this.Name + "\t" + "Id:" + this.Id;
        }

    }
}
//Running Result:

//Name:tom        Id:100
//Name:jhon       Id:99
//Name:james      Id:101
2.索引器
using System;
using System.Collections.Generic;
namespace Csharp_how_to
{
    class Program
    {
        static void Main(string[] args)
        {

            var team = new BaseballTeam
            {
                ["RF"] = "Jhon",
                [4] = "Danie",
                ["CF"] = "Mike",
            };

            Console.WriteLine(team[4]);

            Console.ReadKey();
        }
    }
    public class BaseballTeam
    {
        private string[] players = new string[9];
        private readonly List<string> positionAbbreviations = new List<string>()
        {
            "p","C","1B","2B","3B","SS","LF","CF","RF"
        };
        // indexer
        public string this[int position]
        {
            // Baseball positions are 1-9
            get { return players[position - 1]; }
            set { players[position - 1] = value; }
        }
        // indexer

        public string this[string position]
        {
            get { return players[positionAbbreviations.IndexOf(position)]; }
            set { players[positionAbbreviations.IndexOf(position)] = value; }
        }

    }
}
3.通过Collection初始化器初始化字典
using System;
using System.Collections.Generic;
using System.Linq;

namespace Csharp_how_to
{
    class Program
    {
        static void Main()
        {
            var students = new Dictionary<int, StudentName>()
            {
                {111,new StudentName{FirstName="Sachin",LastName="Karnik",Id=211} },
                {112,new StudentName{FirstName="Dina",LastName="Abbas",Id=222} },
                {113,new StudentName{FirstName="Jhon",LastName="Mikle",Id=233} }
            };
            foreach(var index in Enumerable.Range(111,3))
            {
                Console.WriteLine($"Student{index} is {students[index].FirstName}·{students[index].LastName}");
            }

            Console.ReadKey();
        }
    }
    class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Id { get; set; }
    }
    
}
4.Partial Class/Method

对于一些比较大的项目,可以把同一个类分给好几个程序员去编码,最后编译的时候编译器会把标名为partial字样的类会合在一起编译吗,与写进一个class 没有区别。下面以StudentName类为例说名

// 这个部分定义两个属性,姓和名
partial class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    // 这个部分再定义一个属性Id和构造器
    partial class StudentName
    {
        public int Id { get; set; }
        public StudentName(string f,string l,int id)
        {
            this.FirstName = f;
            this.LastName = l;
            this.Id = id;
        }
        public override ToString()
        {
            return "Name:"+this.FirstName+"·"+this.LastName+"\t"+"Id:"+this.Id;
        }
    }
    public static void Main(string[] args)
    {
        Student student=new Student("mikle","Jhon",111);
        Console.WriteLine(student.ToString())
    }

同理,接口也可以分成好几个部分编码,效果同上。以IAnimal接口为例说明

using System;
using System.Collections.Generic;
using System.Linq;

namespace Csharp_how_to
{
    public partial interface IAnimal
    {
         void Eat();
        void Run();
    }
    public partial interface IAnimal
    {
        void Sleep();
        void Shout();
    }

    public class Animal : IAnimal
    {
        public void Eat()
        {
            Console.WriteLine("I am eating");
        }

        public void Run()
        {
            Console.WriteLine("I am running");
        }

        public void Shout()
        {
            Console.WriteLine("I am shouting");
           
        }

        public void Sleep()
        {
            Console.WriteLine("I am slepping");
        }
    }

    class Program
    {
        static void Main()
        {
            Animal animal = new Animal();
            animal.Eat();
            animal.Run();
            animal.Shout();
            animal.Sleep();
            animal.Sleep();
            Console.ReadKey();
        }
    }
}

同理,方法也可以写成Partial

using System;
using System.Collections.Generic;
using System.Linq;
namespace Csharp_how_to
{
    public partial class Animal
    {
      partial void Sleep();
    }
    public partial class Animal
    {
        partial void Sleep()
        {
            Console.WriteLine("ZZZ~~~");
        }
    }
}
5.方法传类参数和结构体参数的区别

因为结构体是值类型的,把一个值类型的数值作为方法的参数传入时会复制一份新的给方法,不会拿到最原始的数据地址,所以结构体作为方法参数时不能对其进行修改。
类是引用类型的,一个类作为方法的参数传入时同样会复制一份出来给方法用,同时这个新复制出来的数值也是指向原先数值的地址,即可以根据这个地址去拿到最先的那个变量,所以可以通过传入的参数来对原来的数字进行修改。下面以实例说明:

using System;
namespace ConsoleApp1
{
    public class TheClass
    {
        public string willIChange;
    }
    public struct TheStrcut
    {
        public string willIChange;
    }
    
    class Program
    {
        static void classTaker(TheClass c)
        {
            c.willIChange = "Changed";
        }
        static void strcutTaker(TheStrcut s)
        {
            s.willIChange = "Changed";
        }

        static void Main(string[] args)
        {
            TheClass testClass = new TheClass();
            TheStrcut testStruct = new TheStrcut();

            testClass.willIChange = "Not Changed";
            testStruct.willIChange = "Not Changed";

            classTaker(testClass);
            strcutTaker(testStruct);

            Console.WriteLine($"Class filed={testClass.willIChange}");
            Console.WriteLine($"Struct filed={testStruct.willIChange}");

            Console.ReadKey();
        }
    }
}

6.运算符重载
using System;
namespace ConsoleApp1
{
    public readonly struct Fraction
    {
        public readonly int num;
        public readonly int den;
        public Fraction(int numerator,int denominator)
        {
            if(denominator==0)
            {
                throw new ArgumentException("Denomintor can not be zero.", nameof(denominator));
            }
            this.num = numerator;
            this.den = denominator;
        }

        // operator overload
        public static Fraction operator +(Fraction a) => a;
        public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);
        public static Fraction operator +(Fraction a, Fraction b) => new Fraction(a.den * b.num + a.num * b.den, a.den * b.den);
        public static Fraction operator -(Fraction a, Fraction b) => a + (-b);
        public static Fraction operator *(Fraction a, Fraction b) => new Fraction(a.num * b.num, a.den * b.den);
        public override string ToString()
        {
            return $"{this.num}/{this.den}";
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            Fraction fraction1 = new Fraction(1, 2);
            Fraction fraction2 = new Fraction(3, 2);
            Console.WriteLine($"{fraction1.ToString()} + {fraction2.ToString()} = {(fraction1+fraction2).ToString()}");
            Console.WriteLine($"-{fraction1.ToString()} = {(-fraction1).ToString()}");
            Console.WriteLine($"{fraction1.ToString()} - {fraction2.ToString()} = {(fraction1-fraction2).ToString()}");
            Console.WriteLine($"{fraction1.ToString()} * {fraction2.ToString()} = {(fraction1*fraction2).ToString()}");

            Console.ReadKey();
        }
    }
}

7.修改一个字符串

字符串在.Net中是不可修改的,对字符串进行的增删的结果都是新生成一个字符串再返回的,下面以实例说明。

using System;
namespace StringModifier
{
    class Program
    {
        var source="The mountains are behind the clouds today.";
        static void Main(string[] args)
        {
            var replaced=source.Replace("behind","front");
            Console.WriteLine($"source:{source}");
            Console.WriteLine($"replaced:{replaced}");
            Console.ReadKey();
        }
    }
}
8.判断一个字符串是不是数值类型的

可以用tryparse方法来进行判断,下面是实例说明:

using System;
namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {

            int i = 0;
            bool res = int.TryParse("2", out i);
            if(res)
            {
                Console.WriteLine($"{i+1}");
            }
            i = 0;
            bool res1 = int.TryParse("we2", out i);
            if (res)
            {
                Console.WriteLine($"{i}");
            }
            Console.ReadKey();
        }
    }
}

9.用LINQ查询ArrayList
using System;
using System.Collections;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
       public int[] Scores { get; set; }
        public override string ToString()
        {
            string res = string.Empty;
            res += "FirstName:" + this.FirstName+"\t";
            res += "LastName:" + this.LastName+"\t";
            for(int i=0;i<this.Scores.Length;i++)
            {
                res += $"第{i+1}个科目成绩为:{this.Scores[i]}"+"\t";
            }
            return res;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {

            ArrayList list = new ArrayList();
            list.Add(new Student { FirstName = "张", LastName = "三", Scores = new int[] { 100, 90 } });
            list.Add(new Student { FirstName = "李", LastName = "四", Scores = new int[] { 98, 90 } });
            list.Add(new Student { FirstName = "张", LastName = "六", Scores = new int[] { 96, 90 } });
            list.Add(new Student { FirstName = "张", LastName = "八", Scores = new int[] { 90, 80 } });

            var query = from Student stu in list
                        where stu.Scores[0] > 95 && stu.FirstName == "张"
                        select stu;
            foreach(var item in query)
            {
                Console.WriteLine(item);
            }


            Console.ReadKey();
        }
    }
}

10.LINQ查询中使用lambda表达式
using System;
using System.Collections;
using System.Linq;
namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {

            // Data source
            int[] scores = new int[] { 100, 50, 60, 70, 40, 98, 78, 69 };

            // The call to count forces iteration of the source
            int highScoreCount = scores.Where(x => x > 90).Count();
            Console.WriteLine(highScoreCount);
            Console.ReadKey();
        }
    }
}


11.LINQ中的运算符All,Any,Contains的用法

All和Any运算符都返回一个布尔类型的结果,All是当所有的数值都满足条件时才会返回True,Any是只要存在满足条件的数值就返回True。Contains是模糊匹配

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Market
    {
        public string Name { get; set; }
        public string[] Items { get; set; }
    }
    class Program
    {

        static void Main(string[] args)
        {
            List<Market> markets = new List<Market>
    {
        new Market { Name = "Emily's", Items = new string[] { "kiwi", "cheery", "banana" } },
        new Market { Name = "Kim's", Items = new string[] { "melon", "mango", "olive" } },
        new Market { Name = "Adam's", Items = new string[] { "kiwi", "apple", "orange" } },
        new Market { Name = "Adam1's", Items = new string[] { "kiwi","yakiwi","apple", "orange" } },
    };

            // Determine which market have all fruit names length equal to 5
            IEnumerable<string> names = from market in markets
                                        where market.Items.All(item => item.Length == 5)
                                        select market.Name;
            // Determine which market have all fruit names length equal to 5
            IEnumerable<string> names2 = from market in markets
                                        where market.Items.Any(item => item.Length == 4)
                                        select market.Name;


            IEnumerable<string> containsNames = from market in markets
                                                where market.Items.Contains("kiwi")
                                                select market.Name;
            Console.WriteLine("All");
            foreach (string name in names)
            {
                Console.WriteLine($"{name} market");
            }
            Console.WriteLine("Any");
            foreach (string name in names2)
            {
                Console.WriteLine($"{name} market");
            }

            Console.WriteLine("Contains");
            foreach(var item in containsNames)
            {
                Console.WriteLine(item);
            }
        }
    }

}


12.LINQ中使用排序
  • 按照一个值来排序
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string Name { get; set; }
        public int Score { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            for(int i=0;i<30;i++)
            {
                Student stu = new Student
                {
                    Name = "Name" + i.ToString(),
                    Score = new Random().Next(100)
                };
                students.Add(stu);
            }

            var query = from Student stu in students
                        where stu.Score > 60//过滤成绩几个的同学
                        orderby stu.Score//按成绩排序
                        select stu;
            foreach (var item in query)
            {
                Console.WriteLine("Name:"+item.Name+"\t"+"Score:"+item.Score);
            }

            Console.ReadKey();
        }
    }

}
// 运行结果
Name:Name1      Score:74
Name:Name14     Score:76
Name:Name16     Score:76
Name:Name23     Score:76
Name:Name2      Score:77
Name:Name13     Score:86
Name:Name21     Score:88
Name:Name22     Score:91
Name:Name3      Score:92
Name:Name20     Score:93
  • 按照里两个值来排序,如果数学成绩相等,再比较文化课成绩
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string Name { get; set; }
        public int MathScore { get; set; }
        public int CultureScore { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            for(int i=0;i<30;i++)
            {
                Student stu = new Student
                {
                    Name = "Name" + i.ToString(),
                    MathScore = new Random().Next(90,100),
                    CultureScore = new Random().Next(100),
                };
                students.Add(stu);
            }

            var query = from Student stu in students
                        where stu.MathScore > 60 && stu.CultureScore>60
                        orderby stu.MathScore,stu.CultureScore
                        select stu;
            foreach (var item in query)
            {
                Console.WriteLine("Name:"+item.Name+"\t"+"MathScore:"+item.MathScore+"\t"+"CultureScore:"+item.CultureScore);
            }

            Console.ReadKey();
        }
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值