扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
Console.WriteLine("Theemployee:{0},thecountervalue:{1}", myEmployee,myCounter); |
Theemployee:Employee,thecountervalue:12 |
usingSystem; //不覆盖ToString的类 publicclassEmployee { } //覆盖了ToString的类 publicclassCounter { privateinttheVal; publicCounter(inttheVal) { this.theVal=theVal; } publicoverridestringToString() { Console.WriteLine("CallingCounter.ToString()"); returntheVal.ToString(); } } publicclassTester { publicstaticvoidMain() { //创建类的实例 Testert=newTester(); //调用非静态成员 //(mustbethroughaninstance) t.Run(); } //演示调用ToString的非静态方法 publicvoidRun() { EmployeemyEmployee=newEmployee(); CountermyCounter=newCounter(12); Console.WriteLine("Theemployee:{0},thecountervalue:{1}", myEmployee,myCounter); intmyInt=5; Console.WriteLine("Herearetwointegers:{0}and{1}",17,myInt); } } |
publicvoidGetStats(refintage,refintID,refintyearsServed) |
Fred.GetStats(refage,refID,refyearsServed); |
publicvoidGetStats(outintage,outintID,outintyearsServed) |
Fred.GetStats(outage,outID,outyearsServed); |
usingSystem;//有二个成员变量和一个构造器的简单结构 publicstructPoint { publicPoint(intx,inty) { this.x=x; this.y=y; } publicintx; publicinty; } publicclassTester { publicstaticvoidMain() { Testert=newTester(); t.Run(); } publicvoidRun() { Pointp1=newPoint(5,12); SomeMethod(p1);//fine Pointp2;//不调用new而直接创建 //编译器编译到这里时会出错,因为p2的成员变量没有被初始化 //SomeMethod(p2); //手工对它们进行初始化 p2.x=1; p2.y=2; SomeMethod(p2); } //一个可以接受Point作为参数的方法 privatevoidSomeMethod(Pointp) { Console.WriteLine("Pointat{0}x{1}", p.x,p.y); } } |
publicintAge { get { returnage; } set { age=value; } } |
Fred.Age=17; |
publicintYearsServed { get { returnyearsServed; } }Accessors的使用 privatevoidRun() { EmployeeFred=newEmployee(25,101,7); Console.WriteLine("Fred''sage:{0}", Fred.Age); Fred.Age=55; Console.WriteLine("Fred''sage:{0}", Fred.Age); Console.WriteLine("Fred''sservice:{0}", Fred.YearsServed); //Fred.YearsServed=12;//是不被允许的 } |
int[]myIntArray=newint[5]; |
int[]myIntArray={2,4,6,8,10}; |
int[,]myRectangularArray=newint[rows,columns]; |
int[,]myRectangularArray= { {0,1,2},{3,4,5},{6,7,8},{9,10,11} }; |
int[][]myJaggedArray=newint[4][]; |
myJaggedArray[0]=newint[5]; myJaggedArray[1]=newint[2]; myJaggedArray[2]=newint[3]; myJaggedArray[3]=newint[5]; |
stringtheFirstString=myListBox[0]; stringtheLastString=myListBox[Length-1]; |
Figure5ListBoxClass usingSystem; //简化的ListBox控制 publicclassListBoxTest { //用字符串初始化该ListBox publicListBoxTest(paramsstring[]initialStrings) { //为字符串分配空间 myStrings=newString[256]; //把字符串拷贝到构造器中 foreach(stringsininitialStrings) { myStrings[myCtr++]=s; } } //在ListBox的末尾添加一个字符串 publicvoidAdd(stringtheString) { myStrings[myCtr++]=theString; } publicstringthis[intindex] { get { if(index<0||index>=myStrings.Length) { //处理有问题的索引 } returnmyStrings[index]; } set { myStrings[index]=value; } } //返回有多少个字符串 publicintGetNumEntries() { returnmyCtr; } privatestring[]myStrings; privateintmyCtr=0; } publicclassTester { staticvoidMain() { //创建一个新的列表并初始化 ListBoxTestlbt=newListBoxTest("Hello","World"); //添加一些新字符串 lbt.Add("Who"); lbt.Add("Is"); lbt.Add("John"); lbt.Add("Galt"); stringsubst="Universe"; lbt[1]=subst; //访问所有的字符串 for(inti=0;i Console.WriteLine("lbt[{0}]:{1}",i,lbt[i]); } } } |
publicIEnumeratorGetEnumerator() { return(IEnumerator)newListBoxEnumerator(this); } |
publicListBoxEnumerator(ListBoxTesttheLB) { myLBT=theLB; index=-1; } |
publicboolMoveNext() { index++; if(index>=myLBT.myStrings.Length) returnfalse; else returntrue; } |
publicobjectCurrent { get { return(myLBT[index]); } } |
myStrings=newString[8]; |
usingSystem; usingSystem.IO; usingSystem.Text; |
publicclassAsynchIOTester { privateStreaminputStream; privatebyte[]buffer; privateAsyncCallbackmyCallBack; |
publicdelegatevoidAsyncCallback(IAsyncResultar); |
voidOnCompletedRead(IAsyncResultasyncResult) |
AsynchIOTester() { ??? myCallBack=newAsyncCallback(this.OnCompletedRead); } |
publicstaticvoidMain() { AsynchIOTestertheApp=newAsynchIOTester(); theApp.Run(); } |
AsynchIOTester() { inputStream=File.OpenRead(@"C:\MSDN\fromCppToCS.txt"); buffer=newbyte[BUFFER_SIZE]; myCallBack=newAsyncCallback(this.OnCompletedRead); } |
inputStream.BeginRead( buffer,//存放结果 0,//偏移量 buffer.Length,//缓冲区中有多少字节 myCallBack,//回调代理 null);//本地对象 |
for(longi=0;i<50000;i++) { if(i%1000==0) { Console.WriteLine("i:{0}",i); } } |
voidOnCompletedRead(IAsyncResultasyncResult) { |
intbytesRead=inputStream.EndRead(asyncResult); |
if(bytesRead>0) { Strings=Encoding.ASCII.GetString(buffer,0,bytesRead); Console.WriteLine(s); inputStream.BeginRead(buffer,0,buffer.Length, myCallBack,null); } |
TCPListenertcpListener=newTCPListener(65000); |
tcpListener.Start(); |
SocketsocketForClient=tcpListener.Accept(); |
if(socketForClient.Connected) { ??? |
NetworkStreamnetworkStream=newNetworkStream(socketForClient); |
System.IO.StreamWriterstreamWriter= newSystem.IO.StreamWriter(networkStream); |
TCPClientsocketForServer; socketForServer=newTCPClient("localHost",65000); |
NetworkStreamnetworkStream=socketForServer.GetStream(); System.IO.StreamReaderstreamReader= newSystem.IO.StreamReader(networkStream); |
do { outputString=streamReader.ReadLine(); if(outputString!=null) { Console.WriteLine(outputString); } } while(outputString!=null); |
Thisislineone Thisislinetwo Thisislinethree Thisislinefour |
Output(Server) Clientconnected SendingThisislineone SendingThisislinetwo SendingThisislinethree SendingThisislinefour Disconnectingfromclient... Exiting... |
Thisislineone Thisislinetwo Thisislinethree Thisislinefour |
[assembly:AssemblyDelaySign(false)] [assembly:AssemblyKeyFile(".\\keyFile.snk")] |
[assembly:AssemblyDelaySign(false), assembly:AssemblyKeyFile(".\\keyFile.snk")] |
//Bug323fixedbyJesseLiberty1/1/2005. |
[BugFix(323,"JesseLiberty","1/1/2005")Comment="Offbyoneerror"] |
[AttributeUsage(AttributeTargets.ClassMembers,AllowMultiple=true)] |
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface,AllowMultiple=true)] |
[BugFix(123,"JesseLiberty","01/01/05",Comment="Offbyone")] |
publicBugFixAttribute(intbugID,stringprogrammer,stringdate) { this.bugID=bugID; this.programmer=programmer; this.date=date; } Namedparametersareimplementedasproperties. |
[BugFixAttribute(121,"JesseLiberty","01/03/05")] [BugFixAttribute(107,"JesseLiberty","01/04/05", Comment="Fixedoffbyoneerrors")] publicclassMyMath |
usingSystem; //创建被指派给类成员的自定义属性 [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] publicclassBugFixAttribute:System.Attribute { //位置参数的自定义属性构造器 publicBugFixAttribute (intbugID, stringprogrammer, stringdate) { this.bugID=bugID; this.programmer=programmer; this.date=date; } publicintBugID { get { returnbugID; } } //命名参数的属性 publicstringComment { get { returncomment; } set { comment=value; } } publicstringDate { get { returndate; } } publicstringProgrammer { get { returnprogrammer; } } //专有成员数据 privateintbugID; privatestringcomment; privatestringdate; privatestringprogrammer; } //把属性指派给类 [BugFixAttribute(121,"JesseLiberty","01/03/05")] [BugFixAttribute(107,"JesseLiberty","01/04/05", Comment="Fixedoffbyoneerrors")] publicclassMyMath { publicdoubleDoFunc1(doubleparam1) { returnparam1+DoFunc2(param1); } publicdoubleDoFunc2(doubleparam1) { returnparam1/3; } } publicclassTester { publicstaticvoidMain() { MyMathmm=newMyMath(); Console.WriteLine("CallingDoFunc(7).Result:{0}", mm.DoFunc1(7)); } } |
CallingDoFunc(7).Result:9.3333333333333339 |
System.Reflection.MemberInfoinf=typeof(MyMath); |
object[]attributes; attributes=Attribute.GetCustomAttributes(inf,typeof(BugFixAttribute)); |
publicstaticvoidMain() { MyMathmm=newMyMath(); Console.WriteLine("CallingDoFunc(7).Result:{0}", mm.DoFunc1(7)); //获取成员信息并使用它访问自定义的属性 System.Reflection.MemberInfoinf=typeof(MyMath); object[]attributes; attributes= Attribute.GetCustomAttributes(inf,typeof(BugFixAttribute)); //遍历所有的属性 foreach(Objectattributeinattributes) { BugFixAttributebfa=(BugFixAttribute)attribute; Console.WriteLine("\nBugID:{0}",bfa.BugID); Console.WriteLine("Programmer:{0}",bfa.Programmer); Console.WriteLine("Date:{0}",bfa.Date); Console.WriteLine("Comment:{0}",bfa.Comment); } } |
publicstaticAssembly.Load(AssemblyName) |
Assemblya=Assembly.Load("Mscorlib.dll"); |
Type[]types=a.GetTypes(); |
TypeisSystem.TypeCode TypeisSystem.Security.Util.StringExpressionSet TypeisSystem.Text.UTF7Encoding$Encoder TypeisSystem.ArgIterator TypeisSystem.Runtime.Remoting.JITLookupTable 1205typesfound |
publicclassTester { publicstaticvoidMain() { //检查一个对象 TypetheType=Type.GetType("System.Reflection.Assembly"); Console.WriteLine("\nSingleTypeis{0}\n",theType); } } |
SingleTypeisSystem.Reflection.Assembly |
Figure9GettingAllMembers publicclassTester { publicstaticvoidMain() { //检查一个单一的对象 TypetheType=Type.GetType("System.Reflection.Assembly"); Console.WriteLine("\nSingleTypeis{0}\n",theType); //获取所有的成员 MemberInfo[]mbrInfoArray= theType.GetMembers(BindingFlags.LookupAll); foreach(MemberInfombrInfoinmbrInfoArray) { Console.WriteLine("{0}isa{1}", mbrInfo,mbrInfo.MemberType.Format()); } } } |
System.Strings_localFilePrefixisaField BooleanIsDefined(System.Type)isaMethod Void.ctor()isaConstructor System.StringCodeBaseisaProperty System.StringCopiedCodeBaseisaProperty |
MemberInfo[]mbrInfoArray= theType.GetMembers(BindingFlags.LookupAll); |
mbrInfoArray=theType.GetMethods(); |
Output(excerpt) BooleanEquals(System.Object)isaMethod System.StringToString()isaMethod System.StringCreateQualifiedName(System.String,System.String) isaMethod System.Reflection.MethodInfoget_EntryPoint()isaMethod |
publicclassTester { publicstaticvoidMain() { //检查一个单一的对象 TypetheType=Type.GetType("System.Reflection.Assembly"); //只获取以Get开头的成员 MemberInfo[]mbrInfoArray theType.FindMembers(MemberTypes.Method, BindingFlags.Default, Type.FilterName,"Get*"); foreach(MemberInfombrInfoinmbrInfoArray) { Console.WriteLine("{0}isa{1}", mbrInfo,mbrInfo.MemberType.Format()); } } } |
System.Type[]GetTypes()isaMethod System.Type[]GetExportedTypes()isaMethod System.TypeGetType(System.String,Boolean)isaMethod System.TypeGetType(System.String)isaMethod System.Reflection.AssemblyNameGetName(Boolean)isaMethod System.Reflection.AssemblyNameGetName()isaMethod Int32GetHashCode()isaMethod System.Reflection.AssemblyGetAssembly(System.Type)isaMethod System.TypeGetType(System.String,Boolean,Boolean)isaMethod |
TypetheMathType=Type.GetType("System.Math"); |
ObjecttheObj=Activator.CreateInstance(theMathType); |
Type[]paramTypes=newType[1]; paramTypes[0]=Type.GetType("System.Double"); |
MethodInfoCosineInfo= theMathType.GetMethod("Cos",paramTypes); |
Object[]parameters=newObject[1]; parameters[0]=45; ObjectreturnVal=CosineInfo.Invoke(theObj,parameters); |
Type[]paramTypes=newType[0]; |
usingSystem; usingSystem.Reflection;publicclassTester { publicstaticvoidMain() { TypetheMathType=Type.GetType("System.Math"); ObjecttheObj=Activator.CreateInstance(theMathType); //只有一个成员的数组 Type[]paramTypes=newType[1]; paramTypes[0]=Type.GetType("System.Double"); //获得Cos()方法的信息 MethodInfoCosineInfo= theMathType.GetMethod("Cos",paramTypes); //将实际的参数填写在一个数组中 Object[]parameters=newObject[1]; parameters[0]=45; ObjectreturnVal=CosineInfo.Invoke(theObj,parameters); Console.WriteLine( "Thecosineofa45degreeangle{0}",returnVal); } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者