主頁 > .NET開發 > C# 7

C# 7

2020-09-19 00:05:13 .NET開發

 public static class StringHelper
    {
        public static bool IsCapitalized(this string str)
        {
            if(string.IsNullOrWhiteSpace(str))
            {
                return false;
            }
            return char.IsUpper(str[0]);
        }
    }

 static void ExtensionMethodDemo()
        {
            Console.WriteLine("perth".IsCapitalized());
        }

 

 static void LocalMethod()
        {
            Cube(100);
            void Cube(int x) => Console.WriteLine($"The cube of {x} is {x * x * x}");
        }

        
        static void GoToDemo()
        {
            int i = 1;
            startLoop:
            if(i<=5)
            {
                Console.WriteLine(i);
                i++;
                goto startLoop;
            }
        }

deconstructor

class Rectangle
    {
        public readonly float Width, Height;

        public Rectangle(float width,float height)
        {
            Width = width;
            Height = height;
        }

        public void Deconstruct(out float width,out float height)
        {
            width = Width;
            height = Height;
        }
    }

 static void Main(string[] args)
        {
            var rect = new Rectangle(3, 4);
            (float width, float height) = rect;
            Console.WriteLine($"width:{width},height:{height}");
            Console.ReadLine();
        }
 static void Main(string[] args)
        {
            var rect = new Rectangle(3, 4);
            var (width, height) = rect;
            Console.WriteLine($"width:{width},height:{height}");
            Console.ReadLine();
        }
static void Main(string[] args)
        {
            var rect = new Rectangle(3, 4);
            (var width,var height) = rect;
            Console.WriteLine($"width:{width},height:{height}");
            Console.ReadLine();
        }
class Product
    {
        decimal currentPrice, sharesOwned;
        public decimal Worth
        {
            get
            {
                return currentPrice * sharesOwned;
            }
        }

        public decimal Worth2 => currentPrice * sharesOwned;

        public decimal Worth3
        {
            get => currentPrice * sharesOwned;
            set => sharesOwned = value / currentPrice;
        }

public decimal CurrentPrice { get; set; } = 123;


public int Maximum { get; } = 999;


    }


private decimal x;
        public decimal X
        {
            get
            {
                return x;
            }

            private set
            {
                x = Math.Round(value, 2);
            }
        }

Indexer

 class Sentence
    {
        string[] words = "The quick brown fox".Split();

        public string this[int wordNum]
        {
            get
            {
                return words[wordNum];
            }
            set
            {
                words[wordNum] = value;
            }
        }
    }

 static void Main(string[] args)
        {
            Sentence se = new Sentence();
            Console.WriteLine(se[3]);
            se[3] = "kangaroo";
            Console.WriteLine(se[3]);
            Console.ReadLine();
        }
static class StaticClass
    {
        static StaticClass()
        {
            Console.WriteLine("This is the static constructor of the static class!");
        }

        public static DateTime DT = DateTime.Now;
    }

Partial class,partial method.

 partial class PaymentForm
    {
       partial void ValidatePayment(decimal amount);
       public void InvokePartialMethod(decimal amount)
        {
            ValidatePayment(amount);
        }
    }

    partial class PaymentForm
    {
       partial void ValidatePayment(decimal amount)
        {
           if(amount>100)
            {
                Console.WriteLine("Luxury");
            }
            else
            {
                Console.WriteLine("Ok");
            }
        }
    }

static void Main(string[] args)
        {
            PaymentForm pf = new PaymentForm();
            pf.InvokePartialMethod(10);
            pf.InvokePartialMethod(101);
            Console.ReadLine();
        }

 

 internal class Countdown : IEnumerator
    {
        int count = 11;
        public object Current => count;

        public bool MoveNext() => count-- > 0;

        public void Reset()
        {
            throw new NotImplementedException();
        }
    }

static void Main(string[] args)
        {
            IEnumerator e = new Countdown();
            while(e.MoveNext())
            {
                Console.WriteLine(e.Current);
            }
            Console.ReadLine();
        }
 [Flags]
    public enum BorderSides
    {
        None=0,Left=1,Right=2,Top=4,Bottom=8
    }

static void Main(string[] args)
        {
            BorderSides leftRight = BorderSides.Left | BorderSides.Right;
            if((leftRight&BorderSides.Left)!=0)
            {
                Console.WriteLine("Includes Left!");
            }

            string formatted = leftRight.ToString();
            BorderSides s = BorderSides.Left;
            s |= BorderSides.Right;
            Console.WriteLine(s == leftRight);
            Console.ReadLine();
        }
[Flags]
    public enum BSS
    {
        None=0,Left=1,Right=2,Top=4,Bottom=8,
        LeftRight=Left|Right,
        TopBottom=Top|Bottom,
        All=LeftRight|TopBottom
    }

Nested types

public class TopLevel
    {
        public class Nested { }
        public enum Color { Red,Blue,Tan}
    }

static void Main(string[] args)
        {
            TopLevel.Color color = TopLevel.Color.Red;
            Console.WriteLine(color);
            Console.ReadLine();
        }

Generics express reusability with a "Template" that contains "placeholder" types.Generics when compared to inheritance,can increase type safety and reduce casting and boxing.

 public class Stack<T>
    {
        int pos;
        T[] data = new T[100];
        public void Push(T obj) => data[pos++] = obj;
        public T Pop() => data[--pos];
    }

static void Main(string[] args)
{
var stack = new Stack<int>();
stack.Push(5);
stack.Push(10);
WriteLine(stack.Pop());
WriteLine(stack.Pop());


Console.ReadLine();
}

 
static void Main(string[] args)
        {
            Func<int,int,int> fc = AddXY;
            int result = AddXY(10, 20);
            Console.WriteLine(result);
            Console.ReadLine();
        }

        private static int AddXY(int v1, int v2)
        {
            return v1 + v2;
        }

 delegate,eventHandler,eventargs

 public class Stock
    {
        string symbol;
        decimal priceValue;
        public Stock(string symbol)
        {
            this.symbol = symbol;
        }

        public event EventHandler<PriceChangedEventArgs> PriceChanged;

        protected virtual void OnPriceChanged(PriceChangedEventArgs e)
        {
            if(PriceChanged!=null)
            {
                PriceChanged(this, e);
            }
        }

        public decimal Price
        {
            get
            {
                return priceValue;
            }
            set
            {
                if(priceValue=https://www.cnblogs.com/Fred1987/p/=value)
                {
                    return;
                }

                OnPriceChanged(new PriceChangedEventArgs(priceValue, value));
                priceValue = value;                
            }
        }
       
    }

    public class PriceChangedEventArgs : EventArgs
    {
        public readonly decimal LastPrice, NewPrice;
        public PriceChangedEventArgs(decimal lastPriceValue, decimal newPriceValue)
        {
            LastPrice = lastPriceValue;
            NewPrice = newPriceValue;
        }
    }

    public delegate void EventHandler<TEventArgs>(object source, TEventArgs e) where TEventArgs : EventArgs;
}

 

static void Main(string[] args)
        {
            Stock stk = new Stock("SMF");
            stk.Price = 27.10M;
            stk.PriceChanged += StkPriceChanged;
            stk.Price = 39.99M;
            Console.ReadLine();
        }

        private static void StkPriceChanged(object source, PriceChangedEventArgs e)
        {
            decimal rate = ((e.NewPrice - e.LastPrice) / e.LastPrice);
            Console.WriteLine($"The rate is {rate}");
            if((e.NewPrice-e.LastPrice)/e.LastPrice>0.1M)
            {
                Console.WriteLine("Alert,10% price increase!");
            }                
        }

 

public class Stk
    {
        string symbol;
        decimal priceValue;
        public Stk(string symbolValue)
        {
            this.symbol = symbolValue;
        }

        public event EventHandler PriceChanged;
        protected virtual void OnPriceChanged(EventArgs e)
        {
            if(PriceChanged!=null)
            {
                PriceChanged(this, e);
            }
        }

        public decimal Price
        {
            get
            {
                return priceValue;
            }
            set
            {
                if(priceValue=https://www.cnblogs.com/Fred1987/p/=value)
                {
                    return;
                }

                OnPriceChanged(EventArgs.Empty);
                priceValue = value;
            }
        }
    }

    public class Stck
    {
        EventHandler priceChangedHandler;
        public event EventHandler PriceChanged
        {
            add
            {
                priceChangedHandler += value;
            }
            remove
            {
                priceChangedHandler -= value;
            }
        }
    }

    public interface IFoo
    {
        event EventHandler Ev;
    }

    class Foo : IFoo
    {
        EventHandler ev;
        public event EventHandler Ev
        {
            add
            {
                ev += value;
            }
            remove
            {
                ev -= value;
            }
        }
    }

Lambda Expression.

 delegate int Math2Del(int x, int y);

static void Main(string[] args)
        {
            Math2Del add = (x, y) => x + y;
            Console.WriteLine(add(10, 20));

            Math2Del subtract = (x, y) => x - y;
            Console.WriteLine(subtract(10, 20));             
            Console.ReadLine();
        }
delegate void Math3Del(int x, int y);

 static void Main(string[] args)
        {
            Math3Del add = (x, y) =>
            {
                Console.WriteLine($"{x}-{y}={x - y}");
            };
            add(10, 20);
            Console.ReadLine();
        }
static void Main(string[] args)
        {
            Func<int, int> sqrt = x => x * x;
            Console.WriteLine(sqrt(10));

            Func<int, int> cube = (int x) => x * x * x;
            Console.WriteLine(cube(10));
            Console.ReadLine();
        }

 

 static void Main(string[] args)
        {
            Func<string, string, int> totalLength = (s1, s2) => s1.Length + s2.Length;
            Console.WriteLine(totalLength("Hello", "Make every second count!"));
            Console.ReadLine();
        }
 static void Main(string[] args)
        {
            Action<string, string> totalLength = (s1, s2) =>
             {
                 Console.WriteLine($"The sum length of {s1} and {s2} is {s1.Length + s2.Length}");
             };

            totalLength("Wonderful", "Make every second count!");
            Console.ReadLine();
        }
static void Main(string[] args)
        {
            Action<int> cube = x =>
            {
                Console.WriteLine($"The cuble of {x} is {x * x * x}");
            };

            cube(1000);
            Console.ReadLine();
        }

C# closure

static void Main(string[] args)
        {
            Action[] actionArray = new Action[3];
            for(int i=0;i<3;i++)
            {               
                actionArray[i] = () =>
                {
                    Console.WriteLine(i*10);
                };
            }

            foreach(Action act in actionArray)
            {
                act();
            }
            Console.ReadLine();
        }

print 
30
30
30

 

static void Main(string[] args)
        {
            Action[] actionArray = new Action[3];
            for(int i=0;i<3;i++)
            {
                int temp = i;
                actionArray[i] = () =>
                {
                    Console.WriteLine(temp * 10);
                };
            }

            foreach(Action act in actionArray)
            {
                act();
            }
            Console.ReadLine();
        }
 delegate int MathDel(int x);

static void Main(string[] args)
        {
            MathDel cube=(int x)=>{
                return x * x * x;
            };
            Console.WriteLine(cube(10));
            Console.ReadLine();
        }

 

 static void Main(string[] args)
        {
            MathDel cube = x => x * x * x;
            Console.WriteLine(cube(10));
            Console.ReadLine();
        }

 

finally execute the action to dispose resource

static void ReadFile()
        {
            StreamReader reader = null;
            try
            {
                reader = File.OpenText("a.txt");
                if(reader.EndOfStream)
                {
                    return;
                }
                Console.WriteLine(reader.ReadToEnd());
            }

            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
static string ThrowException(string value) =>
            string.IsNullOrWhiteSpace(value) ? throw new ArgumentNullException(nameof(value)) :
            char.ToUpper(value[0]) + value.Substring(1);
 static void GetEnumeratorDemo()
        {
            using(var enumerator="deer".GetEnumerator())
            {
                while(enumerator.MoveNext())
                {
                    var element = enumerator.Current;
                    Console.WriteLine(element);
                }
            }
        }

If the enumerator implements IDisposable, the foreach statement
also acts as a using statement, implicitly disposing the
enumerator object.

 When you implement IEnumerable,you must also implement IEnumerator

public class Person
    {
        public string FirstName;
        public string LastName;
        public Person(string fName,string lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    }

    public class People : IEnumerable
    {
        private Person[] personArrayValue;
        public People(Person[] pArray)
        {
            personArrayValue = new Person[pArray.Length];
            for(int i=0;i<pArray.Length;i++)
            {
                personArrayValue[i] = pArray[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)GetEnumerator();
        }

        public PeopleEnum GetEnumerator()
        {
            return new PeopleEnum(personArrayValue);
        }
    }

    //When you implement IEnumerable,you must also implement IEnumerator
    public class PeopleEnum : IEnumerator
    {
        public Person[] PersonArray;

        //Enumerators are positioned before the first element
        //until the first MoveNext() call.
        int pos = -1;

        public PeopleEnum(Person[] personArrayValue)
        {
            PersonArray = personArrayValue;
        }       

        public bool MoveNext()
        {
            pos++;
            return (pos < PersonArray.Length);
        }

        public void Reset()
        {
            pos = -1;
        }

        public Person Current
        {
            get
            {
                try
                {
                    return PersonArray[pos];
                }
                catch(IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }
}

static void IEnumerableDemo()
        {
            Person[] personArray = new Person[3]
            {
                new Person("Fred1", "Fu"),
                new Person("Fred2", "Fu"),
                new Person("Fred3", "Fu")
            };

            People peopleList = new People(personArray);
            foreach(Person p in peopleList)
            {
                Console.WriteLine($"FirstName:{p.FirstName},LastName:{p.LastName}");
            }
        }
    

 

succinctly
terse
brief
concise

static void Main(string[] args)
        {
            foreach(int fib in Fibs(10))
            {
                Console.Write(fib+"\t");
            }
            Console.ReadLine();
        }

        static IEnumerable<int> Fibs(int fibCount)
        {
            for (int i = 0, prevFib = 1, curFib = 1;i<fibCount;i++)
            {
                yield return prevFib;
                int newFib = prevFib + curFib;
                prevFib = curFib;
                curFib = newFib;
            }
        }
static void Main(string[] args)
        {
            foreach(string s in FooString())
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();
        }

        static IEnumerable<string> FooString()
        {
            yield return "One";
            yield return "Two";
            yield return "Three";
        }

 

The yield break statement indicates that the iterator block should exit early.

static void Main(string[] args)
        {
            foreach(string s in YieldBreak(true))
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();
        }

        static IEnumerable<string> YieldBreak(bool breakEarly)
        {
            yield return "One";
            yield return "Two";
            if(breakEarly)
            {
                yield break;
            }
            yield return "Three";
        }
static void Main(string[] args)
        {
            IEnumerable<int> data = https://www.cnblogs.com/Fred1987/p/Enumerable.Range(0, 100000);
            foreach(var i in EvenNumberOnly(data))
            {
                Console.Write(i + "\t");
            }
            Console.ReadLine();
        }

        static IEnumerable<int> EvenNumberOnly(IEnumerable<int> sequence)
        {
            foreach(int x in sequence)
            {
                if((x%2)==0)
                {
                    yield return x; 
                }
            }
        }
static void Main(string[] args)
        {
            IEnumerable<int> data = https://www.cnblogs.com/Fred1987/p/Enumerable.Range(0, 100000);
            foreach(var i in EvenNumberOnly(data))
            {
                Console.Write(i + "\t");
            }
            Console.ReadLine();
        }

        static IEnumerable<int> EvenNumberOnly(IEnumerable<int> sequence)
        {
            foreach(int x in sequence)
            {
                if((x%2)==0)
                {
                    yield return x; 
                }
            }
        }

 

yield break

 

nullable type

static void NullableDemo()
        {
            int? i = null;
            Console.WriteLine(i == null);
        }
public struct Nullable<T> where T : struct
    {
        public T Value { get; }

        public bool HasValue { get; }

        //public T GetValueOrDefault();

        //public T GetValueOrDefault(T defaultValue);
    }



 static void Main(string[] args)
        {
            Nullable<int> i = new Nullable<int>();
            Console.WriteLine(!i.HasValue);
            Console.ReadLine();
        }

 

C# permits the unboxing of nullable types.

static void Main(string[] args)
        {
            UnboxNullableTypes();
            Console.ReadLine();
        }

        static void UnboxNullableTypes()
        {
            object o = "string";
            int? x = o as int?;
            Console.WriteLine(x.HasValue);
        }

 

 

static void NullableTypesComparison()
        {
            int? x = 5;
            int? y = 10;
            bool isTrue = (x.HasValue && y.HasValue) ?
                (x.Value < y.Value) : false;
            Console.WriteLine(isTrue);
        }

 

 

static void NullableAdd()
        {
            int? a = null;
            int b = 2;
            int? c = a + b;
            Console.WriteLine(c);
            //c is null
        }

 

Annoymous types

static void AnnoymousTypes()
        {
            var fred = new { Name = "Fred", Age = 32, Salary = 100_000_000 };
            Console.WriteLine($"Name={fred.Name},Age={fred.Age},Salary={fred.Salary}");
        }
 static void AnnoymousTypes()
        {
            string title = "architect";
            var fred = new { Name = "Fred", Age = 32, Salary = 100_000_000, title };
            Console.WriteLine($"Name={fred.Name},Age={fred.Age},Salary={fred.Salary},title={fred.title}");
        }
static void AnonymouseArray()
        {
            var dudes = new[]
            {
                new {Name="Fred",Age=32},
                new {Name="Fred2",Age=33}
            };

            foreach(var du in dudes)
            {
                Console.WriteLine($"name:{du.Name},age:{du.Age}");
            }
        }
static void TupleDemo()
        {
            var tuple = ("Fred", 33, "Architect", "CEO");
            Console.WriteLine($"{tuple.Item1},{tuple.Item2},{tuple.Item3},{tuple.Item4}");
        }
static void UnnamedTuple()
        {
            //var is optional
            (string,int) fred= ("Fred", 33);
            Console.WriteLine($"{fred.Item1},{fred.Item2}");
        }
static void Main(string[] args)
        {
            var p = GetPerson();
            Console.WriteLine($"{p.Item1},{p.Item2}");
            Console.ReadLine();
        }

        static (string, int) GetPerson() => ("Fred", 33);

Return tuple from a method.

static void NamedTuples()
        {
            var fred = (Name: "Fred", Age: 33, Title: "CEO");
            Console.WriteLine($"{fred.Name},{fred.Age},{fred.Title}");   
        }
 static void Main(string[] args)
        {
            var p = GetPerson2();
            Console.WriteLine($"{p.name},{p.age}");
            Console.ReadLine();
        }

        //Specify tTuple types 
        static (string name, int age) GetPerson2() =>("Fred", 33);
static void DeconstructTuple()
        {
            var fred = ("Fred", 33);
            (string name, int age) = fred;
            Console.WriteLine($"{name},{age}");

            (string name, int age) fred2 = ("Fred2", 32);
            Console.WriteLine($"{fred2.name},{fred2.age}");
        }
static void LinqQueryNew()
        {
            string[] names = { "Alex", "Fred", "Jim", "James" };
            var query = names.Select(x => new
            {
                Name =x,
                Length=x.Length
            });

            foreach(var row in query)
            {
                Console.WriteLine(row);
            }
        }
static void LinqTakeSkip()
        {
            IEnumerable<int> range = Enumerable.Range(0, 100);
            IEnumerable<int> takeRange = range.Take(10);
            foreach(var i in takeRange)
            {
                Console.Write(i+"\t");
            }

            Console.WriteLine("\n\n\n\n");
            IEnumerable<int> skipRange = range.Skip(10);
            foreach(var i in skipRange)
            {
                Console.Write(i+"\t");
            }
        }
static void LinqFirstLast()
        {
            IEnumerable<int> dataList = Enumerable.Range(0, 1000);
            Console.WriteLine(dataList.First());
            Console.WriteLine(dataList.Last());
            Console.WriteLine($"{dataList.First(x => x % 115 == 1)}");
            Console.WriteLine(dataList.Last(x => x % 888 == 1));
            Console.WriteLine(dataList.ElementAt(10));
        }
static void LinqMaxMinAverage()
        {


IEnumerable<int> dataList = Enumerable.Range(0, 1000);
Console.WriteLine(dataList.Count());
Console.WriteLine(dataList.Count(x => x % 10 == 0));
Console.WriteLine(dataList.Min());
Console.WriteLine(dataList.Max());
Console.WriteLine(dataList.Average());
}



 Linq set union,concat

static void LinqSetDemo()
        {
            int[] seq1 = { 1, 2, 3 };
            int[] seq2 = { 3, 4, 5 };

            IEnumerable<int> concatSeq = seq1.Concat(seq2);
            foreach(int i in concatSeq)
            {
                Console.Write(i+"\t");
            }
            Console.WriteLine();

            IEnumerable<int> unionSeq = seq1.Union(seq2);
            foreach(int i in unionSeq)
            {
                Console.Write(i + "\t");
            }                
        }

Linq intersect,except

static void LinqInsersectExceptDemo()
        {
            int[] seq1 = { 1, 2, 3 };
            int[] seq2 = { 3, 4, 5 };
            IEnumerable<int> intersectSet = seq1.Intersect(seq2);
            foreach(int i in intersectSet)
            {
                Console.Write(i + "\t");
            }
            Console.WriteLine();
            IEnumerable<int> except1 = seq1.Except(seq2);
            foreach(int i in except1)
            {
                Console.Write(i+"\t");
            }
            Console.WriteLine();

            IEnumerable<int> except2 = seq2.Except(seq1);
            foreach(int i in except2)
            {
                Console.Write(i+"\t");
            }
        }

The extra number that we sneaked into the list after  constructing the query is included in the result,because it's not until the foreach statement runs that any filtering or sorting takes place.This is called deferred or lazy evalueation. Deferred execution decouples query construction from query execution,allowing you to construct a query in several steps as well as making it possible to query a database without retrieving all the rows to the client.

static void DeferedExecutingDemo()
        {
            List<int> data = https://www.cnblogs.com/Fred1987/p/new List<int> { 1 };
            IEnumerable<int> query = data.Select(x => x * 10);
            data.Add(2);
            data.Add(3);
            foreach(var a in query)
            {
                Console.WriteLine(a);
            }
        }

static void LinqWhereOrderBySelectDemo()
{
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
IEnumerable<string> query = names.Where(x => x.Contains("a"))
.OrderBy(x => x.Length)
.Select(x => x.ToUpper());
foreach(var a in query)
{
Console.WriteLine(a);
}

IEnumerable<string> query2 = from n in names
where n.Contains("a")
orderby n.Length
select n.ToUpperInvariant();

foreach(var a in query2)
{
Console.WriteLine(a);
}
}

 The let keyword introduces a new variable alongside the range variable.

static void LetDemo()
        {
            string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
            IEnumerable<string> query =
                from n in names
                let vowelless = Regex.Replace(n, "[aeiou]", "")
                where vowelless.Length>2
                orderby vowelless
                select n+"-" +vowelless;
            foreach(var q in query)
            {
                Console.WriteLine(q);
            }

IEnumerable<string> query2 =
names.Select(x => new
{
x = x,
vowelless = Regex.Replace(x, "[aeiou]", "")
})
.Where(temp => (temp.vowelless.Length > 2))
.OrderBy(temp => temp.vowelless)
.Select(temp => ((temp.x + "-") + temp.vowelless));


        }

 

static void MultipleGeneratorsDemo()
        {
            int[] numbers = { 1, 2, 3 };
            string[] letters = { "a", "b" };

            IEnumerable<string> query = from n in numbers
                                        from l in letters
                                        select n.ToString() + l;
            foreach(var q in query)
            {
                Console.WriteLine(q);
            }

            IEnumerable<string> selectMany = numbers.SelectMany
                (x => letters,
                (x, l) => (x.ToString() + l));

            foreach(var a in selectMany)
            {
                Console.WriteLine(a);
            }

            string[] players = { "Tom", "Jay", "Mary" };
            IEnumerable<string> compare = from n1 in players
                                          from n2 in players
                                          where n1.CompareTo(n2) < 0
                                          orderby n1, n2
                                          select n1 + " vs " + n2;

            foreach(var a in compare)
            {
                Console.WriteLine(a);
            }

            string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
            IEnumerable<string> q3 = from fn in fullNames
                                     from name in fn.Split()
                                     select name + " comes from " + fn;
            foreach (string ne in q3)
            {
                Console.WriteLine(ne);
            }
        }

 

static void LinqAnnoymousTypes()
        {
            var customers = new[]
            {
                new { Id = 1, Name = "Tom" },
                new { Id = 2, Name = "Dick" },
                new { Id = 3, Name = "Harry" }
            };

            var purchases = new[]
            {
                new {CID=1,Product="House"},
                new {CID=2,Product="Car"},
                new {CID=2,Product="Mansion"},
                new {CID=4,Product="Holiday"}
            };

            IEnumerable<string> query =
                from c in customers
                join p in purchases on c.Id equals p.CID
                select c.Name + " bought a " + p.Product;

            foreach(var q in query)
            {
                Console.WriteLine(q);
            }

            IEnumerable<string> query2 = from c in customers
                                         from p in purchases
                                         where c.Id == p.CID
                                         select c.Name + " bought a " + p.Product;

            foreach(var a in query2)
            {
                Console.WriteLine(a);
            }
        }

 

 static void LinqZipDemo()
        {
            int[] nums = { 3, 5, 7 };
            string[] words = { "three", "five", "seven", "ignored" };

            IEnumerable<string> zip = nums.Zip(words, (n, v) => n + "=" + v);
            foreach(var z in zip)
            {
                Console.WriteLine(z);
            }
        }

 

static void LinqOrderDemo()
{
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
IEnumerable<string> query = from n in names
orderby n.Length,n
select n;
foreach(var q in query)
{
Console.WriteLine(q + " " + q.Length);
}

IEnumerable<string> query2 = names.OrderBy(x => x.Length).ThenBy(x => x);
foreach(var n in query2)
{
Console.WriteLine(n);
}
}

static void LinqGroupDemo()
        {
            string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
            var query = from name in names
                        group name by name.Length;

            foreach(IGrouping<int,string> g in query)
            {
                Console.Write("\r\n Length= " + g.Key + ":");
                foreach(string name in g)
                {
                    Console.Write(" " + name);
                }
            }

            Console.WriteLine("\n\n\n\n\n");
            var query2 = names.GroupBy(x => x.Length);
            foreach(IGrouping<int,string> g in query2)
            {
                Console.WriteLine("Length=" + g.Key);
                foreach(string name in g)
                {
                    Console.WriteLine(name);
                }
            }
        }

 

static void TaskGetAwaiterDemo()
        {
            Task<int> task = ComplexcalculationAsync();
            var awaiter = task.GetAwaiter();
            awaiter.OnCompleted(() =>
            {
                int result = awaiter.GetResult();
                Console.WriteLine(result);
            });
        }

        static Task<int> ComplexcalculationAsync()
        {
            return Task.Run(() => ComplexCalculation());
        }

        static int ComplexCalculation()
        {
            double x = 2;
            for (int i = 1; i < 100000000; i++)
            {
                x += Math.Sqrt(x) / i;
            }               
            return (int)x;
        }

 

The expression upon which you await is typically a task;however,any object with a GetAwaiter method that returns an awaitable object-implementing INotifyCompletion.OnCompleted and with an appropriately typed GetResult method and a bool IsCompleted property that tests for synchronous completion will satisfy the compiler.

static void Main(string[] args)
        {
            Console.WriteLine($"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")} Begin");
            Task.Delay(5000);
            Console.WriteLine($"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")} End");
            Console.ReadLine();
        }
static async void TaskWhenAll()
        {
            await Task.WhenAll(GetIntTask(), GetIntTask());
            Console.WriteLine("Done");
        }
static async void TaskWhenAll()
        {
            await Task.WhenAll(GetIntTask(), GetIntTask());
            Console.WriteLine("Done");
        }
static async void FuncAsync()
        {
            await unnamed();
            await NamedTaskMethod();
        }

        static Func<Task> unnamed = async () =>
        {
            await Task.Delay(2000);
            Console.WriteLine("Unnamed!");
        };

        static async Task NamedTaskMethod()
        {
            await Task.Delay(5000);
            Console.WriteLine("Done");
        }

The unsafe  code,pointer.

The fixed statement is required to pin a managed object such as the bitmap in the previous example. The fixed statement tells the garbage collector to pin the object and not move it around. Whithin a fixed statement,you can get a pointer to a value type an array of value types,or a string.

static void Main(string[] args)
        {
            UnsafeMethod();
            Console.ReadLine();
        }

        int x;

        unsafe static void UnsafeMethod()
        {
            Program obj = new Program();
            fixed (int* p = &obj.x)
            {
                *p = 9;
            }
            Console.WriteLine(obj.x);
        }

 

In addition to the & and * ,operators,C# also provides the C++ style ->operator which can be used on structs.

struct Test
    {
        int x;
        unsafe static void Main()
        {
            Test test = new Test();
            Test* p = &test;
            p->x = 9;
            Console.WriteLine(test.x);
        }
    }

 

The stackalloc keyword  can help you allocate memory in a block on the stack explicitly.

unsafe static void StackAllocDemo()
        {
            int* a = stackalloc int[10];
            for(int i=0;i<10;i++)
            {
                Console.WriteLine(a[i]);
            }
        }

 

//allocate a block of memory within a struct
        unsafe struct UnsafeUnicodeString
        {
            public short length;
            public fixed byte buffer[30];
        }
//allocate a block of memory within a struct
        unsafe struct UnsafeUnicodeString
        {
            public short length;
            public fixed byte buffer[30];
        }

        //keyword is also used in this example to pin the object on 
        // the heap that contains the buffer

        unsafe class UnsafeClass
        {
            UnsafeUnicodeString uus;

            public UnsafeClass(string str)
            {
                uus.length = (short)str.Length;
                fixed(byte* p=uus.buffer)
                {
                    for(int i=0;i<str.Length;i++)
                    {
                        p[i] = (byte)str[i];
                        Console.WriteLine(p[i]);
                    }
                }
            }
        }
unsafe static void UnsafeVoidDemo()
        {
            short[] a = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
            fixed(short* p=a)
            {
                Zap(p, a.Length * sizeof(short));
            }

            foreach(short x in a)
            {
                Console.WriteLine(x);
            }
        }

        //A void pointer(void *) makes no assumptions about the type of 
        //the underlying data and is useful for functions that deal with raw memory
        unsafe static void Zap(void* memory,int byteCount)
        {
            byte* b = (byte*)memory;
            for(int i=0;i<byteCount;i++)
            {
                *b++ = 0;
            }
        }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


轉載請註明出處,本文鏈接:https://www.uj5u.com/net/77409.html

標籤:C#

上一篇:Unity3d組件實作令人驚嘆的像素粒子特效!

下一篇:SynchronizationContext(同步背景關系)綜述

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more