zoukankan      html  css  js  c++  java
  • C#笔记-随手记

    11. 字符串前加 @ 字符串中是字面量,转义字符串不会被求值,例外的是相邻的双引号,他们被解释为单个双引号,
    string rst = "value 1 	 5, val2 	 10";
    string vst = @"value 1 	 5,“” val“” 2 	 10"; //不解释制表符
    
    
    12. 定义类的转换,重载运算符
    	
    class LimitedInt
    {
    	private int _value = 9;
    	public static implicit operator int (LimitedInt li)
    	{
    		return li._value;
    	}
    	public static implicit operator LimitedInt(int x)
    	{
    		var li = new LimitedInt();
    		li._value = x;
    		return li;
    	}
    	public static LimitedInt operator + (LimitedInt x , double y)
    	{
    		LimitedInt li = new LimitedInt();
    		li._value = x._value + (int)y;
    		return li;
    	}
    	
    }
    
    13. typeof运算符
    using System.Reflection;
    
    class Program
    {
    	static voic main()
    	{
    		Type t = typeof(LimitedInt);
    		FieldInfop[] fi = t.GetFields();
    		MethodInfo[] mi = t.GetMethods();
    		var s = new LimitedInt();
    		foreach(MethodInfo m in mi)
    			Console.WriteLine("Method:{0}", m.Name);
    		Console.writeLine("{0}", s.GetType().Name);
    		
    
    
    
    	}
    }
    
    
    14. using语句帮助减少意外的运行时错误带来的潜在问题,包装了资源的使用。它执行下列内容:
    *分配资源
    *statement放进try块
    *创建资源的Dispose 方法的调用, 并把它放进finally块
    
    class Program
    {
    	using(TextWriter tw1 = File.Createtext("aaa.txt"),
    			tw2 = File.CreateText("bbb.txt"))
    	{
    		tw1.WriteLine("for score and seven years ago, ... ");
    		tw2.writeLine("early to bed; early to rise .. ");
    	}
    	using(TextReader tr1 = File.OpenText("aaa.txt"),
    			tr2 = File.OpenText("bbb.txt"))
    	{
    		string InputString;
    		while( null != (InputString = tr1.ReadLine()))
    			console.WriteLine(InputSring);
    		while( null != (InputStinrg = tr2.ReadLine()))
    			COnsole.WriteLine(InputString);
    	}
    }
    
    》结构是值类型, 结构本身派生自System.ValueType > object
    
    》enum [Flasgs]特性,不会改变计算结果, 但却提供了一些方便的特性,
    》》它能知编译器,该枚举成员不公可以用作单独的值, 还可以按位标志进行组合,
    》》它允许枚举的ToString的方法为位标志的值提代更多的格式化信息。
    》
    

      

    delegate int OtherDel(int InParam);
    static void Main()
    {
        OtherDel del = delegate(int x)
        {
            return x+20;
        }
        //...
    }
    
    delegate void SomeDel(int x);
    SomeDel sDel = delegate
        {
            Console.WriteLine("......."):
        };
    
    
    事件处理程序的规范可以是:
    》》实例方法的名称;
    》》静态方法的名称;
    》》匿名方法;
    》》Lambda表达式;
    
    
    
    
    interface IInfo
    {
        string GetName();
        string GetAge();
    }
    
    class Ca : IInfo
    {
        public string Name;
        public int Age;
        public string GetName(){ return Name; }
        public string GetAge(){ return Age.ToString(); }
    
    }
    
    class Cb : IInfo
    {
        public string First;
        public string Last;
        public string GetName() {return First + "" + Last;}
        public string GetAge() {return "99";}
    }
    
    class Program
    {
    
        static void PrintInfo(IInfo item)
        {
            string n = item.GetName();
            string a = item.GetAge();
        }
    
        static void main(){
    
            Ca a = new Ca(){ Name = "xxx", Age = 22 };
            Cb b = new Cb(){ First = "aaa", Last = "bbb" };
            PrintInfo(a);
            PrintInfo(b);
    
        }
    }
    》装箱转换
    
     装箱是返回的是值的引用类型副本,不是在原值上操作,原始值类型和引用类型副本。
    
     》拆箱unboxing 是把装箱后的对象转换回值类型的过程,显示转换
    
    
    》自定义类型的转换
    public static implicit operator int (Person p) //将person 隐式转换为int,
    {
        return p.Age;
    }
    public static explicit operator int (Person p) //必须强制类型转换
    is 判定是否可以转换,只可以用于引用转换以及装箱,拆箱转换, 不能用于用户自定义转换。
    
    》as 运算符和强制转换运算符类似,只是不抛出异常, 失败返回null, 只能用于引用转换和装箱转换,
        不能用于用户自定义转换或到值类型的转换。
    
    /*
    》泛型
    声明:
    在类名之后旋转一组尖括号。
    在尖括号中用逗号分隔的占位符字符串来表示希望提供的类型。叫类型参数。
    在泛型类声明的主体中使用类型参数来表示应该替代的类型
    */
    class SomeClass <T1, T2>
    {
        public t1 someVar = new T1();
        public T2 otherVar = new T2();
    }
    
    
    
    class MyStack<T>
    {
        T[] StackArray;
        int StackPointer = 0;
        public void Push(T x)
        {
            if(!IsStackFull)
                StackArray[StackPointer++] = x;
        }
        public T Pop()
        {
            return (!isStackEmpty) ? StackArray[--StackPointer] : StackArray[0];
        }
    
        const int MaxStack = 10;
        bool IsStackFull { get{ return StackPointer >= MaxStack;}}
        bool IsStackEmpty{ get{ return StackPointer <= 0;}}
        public  MyStack()
        {
            StackArray = new T[MaxStack];
        }
        public void Print()
        {
            for(int i = StackPointer - 1; i >= 0; i-- )
            {
                Console.WriteLine(" Value : {0}", StackArray[i]);
            }
        }
    }
    
    
    class Program
    {
        static void Main()
        {
            MyStack<int> StackInt = new MyStack<int>();
            MyStack<string> StackString = new MyStack<string>();
            StackInt.Push(1);
            StackString.Push("so fun");
            StackString.Print();
        }
    }
    
    }
    
    
    
    
    扩展方法和泛型类
    
    static class ExtendHolder
    {
        pulbic static void Print<T>(this Holder<T> h)
        {
            T[] vals = h.GetValues();
            Console.WriteLine("......");
        }
    }
    
    
    class Holder<T>
    {
        T[] Vals = new T[3];
        public Holder(T v0, T v1, T v2)
        {
            Vals[0] = v0; vals[1] = v1;
        }
        public T[] GetValues() {return Vals;}
    }
    
    class Program
    {
        static void main(string[] args)
        {
            var intHolder = new Holder<int>(3, 4,5 );
            var stringHolder = new Holder<string>("a1", "b2", "c3");
            intHolder.Print();
            stringHolder.Print();
        }
    }
    
    //泛型委托
    delegate void MyDelegate<T>(T value);
    class Simple
    {
        static public void PrintString(string s)
        {
            Console.WriteLine(s);
        }
        static public void PrintUpperString( string s)
        {
            ;
        }
    }
    
    class Program
    {
    
        static void Main()
        {
            var myDel = new MyDelegate<String>(simple.PrintString);
            myDel += Simple.PrintUpperString;
            
            myDel("Hi there");
    
        }
    }
    
    ///
    public delegate TR Func<T1, T2, TR>(T1 p1, T2 p2);
    
    class Simple
    {
        static public string PrintString(int p1, int p2)
        {
            int total = p1 + p2;
            return total.ToString();
        }
    }
    
    class Program
    {
        static void Main()
        {
            var myDel = new Func<int, int, string>(Simple.PrintString);
            var str = myDel(1, 2);
        }
    }
    
    
    //泛型接品
    
    interface MyTInt<T>
    {
        T ReturnIt( T inValue);
    
    }
    
    class Simple<S> : IMyIfc<S>
    {
        public S ReturnIt(S invalue)
        { return inValue;}
    }
    
    
    //泛型接口的两个额外的能力:
    //》与其它泛型相似, 实瑞不同类型的cdovr泛型接口是不同的接口;
    //》我们可以在非泛型类型中实现泛型接口。
    
    class Simple : IMyIfc<int>, IMyIfc<string>
    {
    
        public int ReturnIt(int inValue)
        { return inValue;}
        public int ReturnIt( string inValue )
        { return inValue;}
    
    }
    //泛型接口的实现必须唯一
    //泛型接口的名字不会和非泛型冲突, 例如, 在前面的代码中我们还可以声明一个名称为ImyIfc的非泛型接口。
    
    
    
    
    //协变convariance 逆变 contravariance  不变 invariance 
    //如果派生类只是用于输出值, 那么这种结构化的委托有效性之间的常数关系叫做协变。
    //为了让编译器知道这是我们的期望, 必须使用out 关键字标记委托声明中的类型参数。
    delegate T Factory<out>();
    //
    //
    //逆变
    
    class Animal { public int NumberOfLegs = 4 ; }
    calss Dog : Animal {}
    
    class Program
    {
        delegate void Action1<in T>(T a);
        static void ActOnAnimal( Animal a ) { Console.WriteLine( a.NumberOfLegs); }
        static void Main()
        {
            Action1<Animal> act1 = ActOnAnimal;
            Action1<Dog> dog1 = act1;
            dog1(new Dog());
        }
    }
    
    //变化只适用于引用类型, 不能从值类型派生其化类型
    //in 和out  关键字只适用于委托和接口,  不适用于类, 结构和方法
    //
    //foreach
    //
    int[] arr1 = { 1, 2,3. 4, 2,2};
    
    foreach ( int item in arr1 )
        Console.WriteLine("Item vale : {0}", item);
    
    //获取一个对象枚举器的方法是调用对象的GetEnumerator 方法, 实现GetEnumerator方法的类型叫做可枚举类型(enumerable type / enumerable) ,数组是可枚举类型。
    
    // Ienumberator 接口
    //包括 MoveNext() Current() Reset()
    
    
    static void main()
    {
    
        int [] myarray = { 1, 2,3 ,4 5 };
        Ienumerator ie = myarray.GetEnumerator();
        while( ie.MoveNext() )
        {
            int i = (int) ie.Current;
            Console.WriteLine("{0}", i);
        }
    }
    
    
    
    
    //Ienumerable 接口  只有一个成员GetEnumberator
    
    using System;
    using System.Collections;
    
    class ColorEnumerator : IEnumerator
    {
        string[] _colors;
        int _position = -1;
        public ColorEnumerator( string[] theColors )
        {
    
            _colors = new string[theColors.Length];
            for( int i = 0 ;i < theColors.Length; i++ )
                _colors[i] = theColors[i];
        }
        
        public object Current
        {
            get
            {
                if( _position == -1)
                    throw new InvalidOperationException();
                if( _position >= _colors.Lenght )
                    throw new InvalidOperationException();
                return _colors[_position];
    
            }
        }
        
        public bool MoveNext()
        {
            if( _position < _colors.Length -1)
            {
                _position++;
                return true;
            }
            else
                return false;
        }
        public void Reset()
        {
            _position = -1;
        }
    }
    
    class Spectrum : Ienumerable
    {
        string[] Colors = {"aaa", "bbb", "ccc", "ddd"};
        public IEnumerator GetEnumerator()
        {
            return new ColorEnumerator(Colors);
        }
    }
    class Program
    {
        static void Main()
        {
            Spectrum spectrum = new Spectrum();
            foreach( string color in spectrum )
                Console.WriteLine(color):
        }
    }
    
    
    
    //迭代器块
    //是有一个或多个yield 语句的代码块。 方法主体;访问器主体; 运算符主体 都可以是迭代器块
    //yield return 语句指定了序列中返回的下一项。
    //yield break 语句指定在序列中没有其他项。
    //
    class MyClass
    {
        public IEnumerator<string> GetEnumerator()
        {
            return BlackAndWhite();
        }
        public IEnumerator<string> BlackAndWhite()
        {
        yield return "black";
        yield return "gray";
        yield return "while";
    
        }
    }
    
    class Program
    {
        static void Main()
        {
            static void Main()
            {
                MyClass mc = new MyClass();
                foreach( string shade in mc)
                    Console.WriteLine(shade);
            }
        }
    }
    
    //将迭代器做为属性
    //
    using System;
    using System.Collections.Generic;
    
    class Spectrum 
    {
        bool _listFromUVtoIR;
        string[] colors = {"red", "green", "blue"};
        
        public Spectrum(bool listFromUVtoIR)
        {
    
            _listFromUVtoIR = listFromUVtoIR;
        }
        public IEnumerator<string> GetEnumerator()
        {
    
            return _listFromUVtoIR ? UVtoIR : IRtoUV;
        }
    
        public IEnumerator<string> UVtoIR
        {
    
            get
            {
                for(int i=0; i< colors.Length; i++)
                    yield return colors[i];
            }
        }
    
        public IEnumerator<string> IRtoUv
        {
            get
            {
                for(int i= colors.Length -1; i>=0; i--)
                    yield return colors[i];
            }
        }
    
    
    
    }
    
    class Program
    {
    
        static void Main()
        {
    
            Spectrum startUV = new Spectrum(true);
            Spectrum startIR = new Spectrum(false);
            foreach (string color in startUV)
                Console.Write("{0}", color);
            Console.WriteLine();
    
    
            foreach( string color in startIR )
                Console.Write("{0}", color );
            Console.WriteLine();
    
    
        }
    }
    
    //迭代器需要System.Collections.Generic命名空间, 因此我们需要使用using 指领引入它
    //Reset方法没有被编译器生成在枚举器中
    //::
    //
    
    
    
    
    
    
    
    
    //匿名类型
    
    class Other
    {
        static public string Name = "Mary Jones";
    }
    
    class Program
    {
        static void Main()
        {
    
            string Major = "history";
    
            var student = new { Age = 19, Other.Name, Major};
            Console.WriteLine("{0}, Age{1}, Major:{2}", student.Name, Student.Age, student.Major);
        }
    }
    
    
    
    //异步编程
    //
  • 相关阅读:
    任天堂确认账户被黑客入侵:开启双重验证是关键,会更加安全
    受疫情影响!美国大量科技初创企业要挨饿或倒闭
    泰国的IPv6功能已从约2%增至30%,部署率位于全球5名
    vue钩子函数
    vue自定义全局指令directive和局部指令directives
    vue自定义按键修饰符
    字符串padStart、padEnd填充
    vue过滤器
    vue指令v-if和v-show
    vue指令v-for和key属性
  • 原文地址:https://www.cnblogs.com/blackcatx/p/6656359.html
Copyright © 2011-2022 走看看