C# 异常处理-finally 和 return

C#异常处理,一般处理方法是 使用  try{}catch{}finally{}来处理。

其中,Finally块的代码是保证会执行的代码。通常,finally块的代码执行try块中要求资源清理的操作。

这里想要说的一点是:finally{}中的内容,在try,catch  中有return的情况下,真的会执行吗?

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                throw new Exception();//若注释掉这行,表示在try块中使用return.
                return;
            }
            catch (Exception )
            {
 
                MessageBox.Show("这是捕获的异常。");
                return;
            }
            finally
            {
                MessageBox.Show("这是finally里面抛出的文字");
            }
        }

运行上面代码,可以看出:

上面代码中,运行的结果,无论return 在try,catch中是否出现,finally中的代码段都是会执行的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Acknowledgments xiii Introduction xv 1. Making Games the Modular Way 1 1.1 Important Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer Class....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-Destruction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spaceship.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemies..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properties...................................................265 11.10 Weapons and Projectiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scenes......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spaceship..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemies..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, James and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari games in the 1980s. I would like to thank everyone at AK Peters/CRC Press for the help and support and for publishing my work. Finally, a massive thank you goes out to you for buying this book and for wanting to do something as cool as to make games. I sincerely hope this book helps your gamemaking adventures—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I wanted. Sometimes I wanted to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packages came along that could either help me in my quest to make games or even make full games for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of games that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create games within their chosen specific genre. If I wanted to do something outside of the limitations of the software, the source code was inaccessible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different types of games but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I wanted to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In essence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in designing a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genres. Prerequisites You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catches. You may want to consider an upgrade to Unity Pro at some point in the future, to take advantage of some of its advanced features, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making less than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D games that may be sold commercially or otherwise. There are no royalties to pay, either. Unity Pro adds a whole host of professional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free doesn’t pack quite enough power, you may also want to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very important point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the examples as simple as possible! This book is about making games, not about learning to program. What This Book Doesn’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniques and concepts offered in this book are meant to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experiences in game development, you make your own rules and draw your own conclusions. Additional material is available from the CRC Press Web site: http://www.crcpress. com/product/isbn/9781466581401. 1 1 Making Games the Modular Way When I first started making games, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a professional developer, landing a job at a game development studio making browser-based games, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great games (both visually and gameplay-wise) very quickly. One secret to his success lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the essentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, resulting in games that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my eyes. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was substantially reduced, which left more time to concentrate on making better games. This book is based on a similar concept of a game-centric framework for use with many different types of games, rather than a set of different games in different styles. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduces recoding, repurposing, or adaptation time. 2 1. Making Games the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different games that use the same framework to make new games, and we can share several of the same core scripts in many different games. The framework takes care of the essentials, and we add a little “glue” code to pull everything together the way we want it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own games, the framework may serve either as a base to build your games on or simply as a tutorial test bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the design decisions of the framework. 1.1 Important Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselves but more because I had solved the problems in a different way that meant I had no real requirement to learn anything new. For most programmers, these concepts will be second nature and perhaps something taught in school, but I did not know how important they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relevant player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finishes. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it makes it easier to migrate them from project to project. Essentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that features a completely different type of gameplay— for example, alien characters running around a track instead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can access it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Important Programming Concepts important to me to design scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and responding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just doesn’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It doesn’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it doesn’t really matter just as long as when you want them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to access), whereas others may be better attached to other scripts. We deal with these on a case-by-case basis. To get things started, we will be looking at some of the ways that these manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistencies in the application of the term in one case versus another. I’ll try my best to keep things logical, but that doesn’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An important part of our manager- and component-based structures is how our scripts are going to communicate with each other. It is inevitable that we will need to access our scripts from a multitude of other areas of the game, which means we should try to provide interfaces that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variables set in the editor by the Inspector window. The easiest way to have your scripts talk to each other is to have direct references to them in the form of public variables within a class. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we want to talk to. Within the class, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Games the Modular Way 2. GameObject referencing using SendMessage. SendMessage is a great way to send a message to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return result. For example, SomeGameObject.SendMessage("DoSomething"); SendMessage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendMessage call. (SendMessageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendMessage("AddScore",2); SomeGameObject.SendMessage("AddScore", SendMessageOptions.RequireReceiver); SomeGameObject.SendMessage("AddScore", SendMessageOptions.DontRequireReceiver); 3. Static variables. The static variable type is useful in that it extends across the entire system; it will be accessible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may want to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variables extend across the entire program, you can have private and public static variables. Things get a little tricky when you try to understand the differences between public and private static types—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be accessed from other classes and other types of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stores a reference to itself in a public static variable like this: gateway = this; 3. In any other class, we can now access the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Important Programming Concepts Private static A private static variable exists within the class it was declared and in any other instances of the same class. Other classes/types of script will not be able to access it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single instance of the player class, to be ready to use for all the other instances of the same class. All player.cs scripts will be able to access the same instance of the PlayerManager. 4. The singleton design pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The biggest danger with this method is that it is possible to create multiple instances of the same script. If this happens, you may find that your player code is talking to the wrong instance of the game controller. A singletonis a commonly used design pattern that allows for only one instance of a particular class to be instantiated at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variables” method earlier in this section, but in implementing a singleton class, we will be adding some extra code to make sure that only one instance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variables can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be accessed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public static function. Other scripts access the public function to gain access to the private static instance of this script, which is returned via the public function so that only one instance of the object will ever exist in a scene regardless of how many components it is attached to and regardless of how many times it is instantiated. A simple singleton structure: public class MySingleton { private static MySingleton instance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Games the Modular Way { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton."); return; } instance = this; } public static MySingleton Instance { get { if (instance == null) { new MySingleton (); } return instance; } } } The singleton instance of our script may be accessed anywhere, by any script, simply with the following syntax: MySingleton.Instance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to describe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The types of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to describe how our car behaves, we may also describe the engine and wheels. These relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car class Wheels function Engine function 7 1.1 Important Programming Concepts
C#学生管理系统 主要代码: (1)自定义函数类代码: public class LinkDataBase { private string strSQL; //与SQL Server 的连接字符串设置 //与数据库的连接 private string connectionString = "server = .;database=stu_Manage;uid=sa;pwd=123"; private static SqlConnection con = new SqlConnection("server = .;database=stu_Manage;uid=sa;pwd=123"); private SqlConnection myConnection; private DataSet ds = new DataSet(); private SqlDataAdapter da; public DataSet SelectDataBase(string tempStrSQL, string tempTableName) //根据输入的SQL语句检索数据库数据 { this.strSQL = tempStrSQL; this.myConnection = new SqlConnection(connectionString); this.da = new SqlDataAdapter(this.strSQL, this.myConnection); this.ds.Clear(); this.da.Fill(ds, tempTableName); //返回填充了数据的DataSet,其中数据表以tempTableName给出的字符串命名 return ds; } public DataTable SelectDataBase(string tempStrSQL) //检索数据库数据(传字符串直接操作数据库) { this.myConnection = new SqlConnection(connectionString); DataSet tempDataSet = new DataSet(); this.da = new SqlDataAdapter (tempStrSQL, this.myConnection); this.da.Fill(tempDataSet); return tempDataSet.Tables[0]; } public void deleteInfo(string strcmd)//删除信息 { SqlCommand cmd = new SqlCommand(strcmd, con); try { con.Open(); if (MessageBox.Show("确定要删除吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { cmd.ExecuteNonQuery(); MessageBox.Show("删除成功!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { con.Close(); } } public void addInfo(string strcmd)//定义添加信息事件 { try { con.Open(); SqlCommand cmd = new SqlCommand(strcmd, con); cmd.ExecuteNonQuery(); MessageBox.Show("添加成功"); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { con.Close(); } } public void updateInfo(string strcmd)//自定义更新信息方法 { try { con.Open(); SqlCommand cmd = new SqlCommand(strcmd, con); cmd.ExecuteNonQuery(); MessageBox.Show("修改成功"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); } } } . . . . . . . . . (2) > . . .
用VS编写的FTP服务器软件,C#网络程序编程学习用。 代码: using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace FtpServer { public partial class FtpServerForm : Form { TcpListener myTcpListener = null; private Thread listenThread; // 保存用户名和密码 Dictionary users; public FtpServerForm() { InitializeComponent(); // 初始化用户名和密码 users = new Dictionary(); users.Add("admin", "admin"); // 设置默认的主目录 tbxFtpRoot.Text = "F:/MyFtpServerRoot/"; IPAddress[] ips = Dns.GetHostAddresses(""); tbxFtpServerIp.Text = ips[5].ToString(); tbxFtpServerPort.Text = "21"; lstboxStatus.Enabled = false; } // 启动服务器 private void btnFtpServerStartStop_Click(object sender, EventArgs e) { if (myTcpListener == null) { listenThread = new Thread(ListenClientConnect); listenThread.IsBackground = true; listenThread.Start(); lstboxStatus.Enabled = true; lstboxStatus.Items.Clear(); lstboxStatus.Items.Add("已经启动Ftp服务..."); btnFtpServerStartStop.Text = "停止"; } else { myTcpListener.Stop(); myTcpListener = null; listenThread.Abort(); lstboxStatus.Items.Add("Ftp服务已停止!"); lstboxStatus.TopIndex = lstboxStatus.Items.Count - 1; btnFtpServerStartStop.Text = "启动"; } } // 监听端口,处理客户端连接 private void ListenClientConnect() { myTcpListener = new TcpListener(IPAddress.Parse(tbxFtpServerIp.Text), int.Parse(tbxFtpServerPort.Text)); // 开始监听传入的请求 myTcpListener.Start(); AddInfo("启动FTP服务成功!"); AddInfo("Ftp服务器运行中...[点击”停止“按钮停止FTP服务]"); while (true) { try { // 接收连接请求 TcpClient tcpClient = myTcpListener.AcceptTcpClient(); AddInfo(string.Format("客户端({0})与本机({1})建立Ftp连接", tcpClient.Client.RemoteEndPoint, myTcpListener.LocalEndpoint)); User user = new User(); user.commandSession = new UserSeesion(tcpClient); user.workDir = tbxFtpRoot.Text; Thread t = new Thread(UserProcessing); t.IsBackground = true; t.Start(user); } catch { break; } } } // 处理客户端用户请求 private void UserProcessing(object obj) { User user = (User)obj; string sendString = "220 FTP Server v1.0"; RepleyCommandToUser(user, sendString); while (true) { string receiveString = null; try { // 读取客户端发来的请求信息 receiveString = user.commandSession.streamReader.ReadLine(); } catch(Exception ex) { if (user.commandSession.tcpClient.Connected == false) { AddInfo(string.Format("客户端({0}断开连接!)", user.commandSession.tcpClient.Client.RemoteEndPoint)); } else { AddInfo("接收命令失败!" + ex.Message); } break; } if (receiveString == null) { AddInfo("接收字符串为null,结束线程!"); break; } AddInfo(string.Format("来自{0}:[{1}]", user.commandSession.tcpClient.Client.RemoteEndPoint, receiveString)); // 分解客户端发来的控制信息中的命令和参数 string command = receiveString; string param = string.Empty; int index = receiveString.IndexOf(' '); if (index != -1) { command = receiveString.Substring(0, index).ToUpper(); param = receiveString.Substring(command.Length).Trim(); } // 处理不需登录即可响应的命令(这里只处理QUIT) if (command == "QUIT") { // 关闭TCP连接并释放与其关联的所有资源 user.commandSession.Close(); return; } else { switch (user.loginOK) { // 等待用户输入用户名: case 0: CommandUser(user, command, param); break; // 等待用户输入密码 case 1: CommandPassword(user, command, param); break; // 用户名和密码验证正确后登陆 case 2: switch (command) { case "CWD": CommandCWD(user, param); break; case "PWD": CommandPWD(user); break; case "PASV": CommandPASV(user); break; case "PORT": CommandPORT(user, param); break; case "LIST": CommandLIST(user, param); break; case "NLIST": CommandLIST(user, param); break; // 处理下载文件命令 case "RETR": CommandRETR(user, param); break; // 处理上传文件命令 case "STOR": CommandSTOR(user, param); break; // 处理删除命令 case "DELE": CommandDELE(user, param); break; // 使用Type命令在ASCII和二进制模式进行变换 case "TYPE": CommandTYPE(user, param); break; default: sendString = "502 command is not implemented."; RepleyCommandToUser(user, sendString); break; } break; } } } } // 想客户端返回响应码 private void RepleyCommandToUser(User user, string str) { try { user.commandSession.streamWriter.WriteLine(str); AddInfo(string.Format("向客户端({0})发送[{1}]", user.commandSession.tcpClient.Client.RemoteEndPoint, str)); } catch { AddInfo(string.Format("向客户端({0})发送信息失败", user.commandSession.tcpClient.Client.RemoteEndPoint)); } } // 向屏幕输出显示状态信息(这里使用了委托机制) private delegate void AddInfoDelegate(string str); private void AddInfo(string str) { // 如果调用AddInfo()方法的线程与创建ListView控件的线程不在一个线程时 // 此时利用委托在创建ListView的线程上调用 if (lstboxStatus.InvokeRequired == true) { AddInfoDelegate d = new AddInfoDelegate(AddInfo); this.Invoke(d, str); } else { lstboxStatus.Items.Add(str); lstboxStatus.TopIndex = lstboxStatus.Items.Count - 1; lstboxStatus.ClearSelected(); } } #region 处理各个命令 #region 登录过程,即用户身份验证过程 // 处理USER命令,接收用户名但不进行验证 private void CommandUser(User user, string command, string param) { string sendString = string.Empty; if (command == "USER") { sendString = "331 USER command OK, password required."; user.userName = param; // 设置loginOk=1为了确保后面紧接的要求输入密码 // 1表示已接收到用户名,等到接收密码 user.loginOK = 1; } else { sendString = "501 USER command syntax error."; } RepleyCommandToUser(user, sendString); } // 处理PASS命令,验证用户名和密码 private void CommandPassword(User user, string command, string param) { string sendString = string.Empty; if (command == "PASS") { string password = null; if (users.TryGetValue(user.userName, out password)) { if (password == param) { sendString = "230 User logged in success"; // 2表示登录成功 user.loginOK = 2; } else { sendString = "530 Password incorrect."; } } else { sendString = "530 User name or password incorrect."; } } else { sendString = "501 PASS command Syntax error."; } RepleyCommandToUser(user, sendString); // 用户当前工作目录 user.currentDir = user.workDir; } #endregion #region 文件管理命令 // 处理CWD命令,改变工作目录 private void CommandCWD(User user, string temp) { string sendString = string.Empty; try { string dir = user.workDir.TrimEnd('/') + temp; // 是否为当前目录的子目录,且不包含父目录名称 if (Directory.Exists(dir)) { user.currentDir = dir; sendString = "250 Directory changed to '" + dir + "' successfully"; } else { sendString = "550 Directory '" + dir + "' does not exist"; } } catch { sendString = "502 Directory changed unsuccessfully"; } RepleyCommandToUser(user,sendString); } // 处理PWD命令,显示工作目录 private void CommandPWD(User user) { string sendString = string.Empty; sendString = "257 '" + user.currentDir + "' is the current directory"; RepleyCommandToUser(user, sendString); } // 处理LIST/NLIST命令,想客户端发送当前或指定目录下的所有文件名和子目录名 private void CommandLIST(User user, string parameter) { string sendString = string.Empty; DateTimeFormatInfo dateTimeFormat = new CultureInfo("en-US", true).DateTimeFormat; // 得到目录列表 string[] dir = Directory.GetDirectories(user.currentDir); if (string.IsNullOrEmpty(parameter) == false) { if (Directory.Exists(user.currentDir + parameter)) { dir = Directory.GetDirectories(user.currentDir + parameter); } else { string s = user.currentDir.TrimEnd('/'); user.currentDir = s.Substring(0, s.LastIndexOf("/") + 1); } } for (int i = 0; i < dir.Length; i++) { string folderName = Path.GetFileName(dir[i]); DirectoryInfo d = new DirectoryInfo(dir[i]); // 按下面的格式输出目录列表 sendString += @"dwr-\t" + Dns.GetHostName() + "\t" + dateTimeFormat.GetAbbreviatedMonthName(d.CreationTime.Month) + d.CreationTime.ToString(" dd yyyy") + "\t" + folderName + Environment.NewLine; } // 得到文件列表 string[] files = Directory.GetFiles(user.currentDir); if (string.IsNullOrEmpty(parameter) == false) { if (Directory.Exists(user.currentDir + parameter + "/")) { files = Directory.GetFiles(user.currentDir + parameter + "/"); } } for (int i = 0; i 1024的随机端口 // 下面这个运算算法只是为了得到一个大于1024的端口值 port = random1 << 8 | random2; try { user.dataListener = new TcpListener(localip, port); AddInfo("TCP 数据连接已打开(被动模式)--" + localip.ToString() + ":" + port); } catch { continue; } user.isPassive = true; string temp = localip.ToString().Replace('.', ','); // 必须把端口号IP地址告诉客户端,客户端接收到响应命令后, // 再通过新的端口连接服务器的端口P,然后进行文件数据传输 sendString = "227 Entering Passive Mode(" + temp + "," + random1 + "," + random2 + ")"; RepleyCommandToUser(user, sendString); user.dataListener.Start(); break; } } // 处理PORT命令,使用主动模式进行传输 private void CommandPORT(User user, string portstring) { // 主动模式时,客户端必须告知服务器接收数据的端口号,PORT 命令格式为:PORT address // address参数的格式为i1、i2、i3、i4、p1、p2,其中i1、i2、i3、i4表示IP地址 // 下面通过.字符串来组合这四个参数得到IP地址 // p1、p2表示端口号,下面通过int.Parse(temp[4]) << 8) | int.Parse(temp[5] // 这个算法来获得一个大于1024的端口来发送给服务器 string sendString = string.Empty; string[] temp = portstring.Split(','); string ipString = "" + temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3]; // 客户端发出PORT命令把客户端的IP地址和随机的端口告诉服务器 int portNum = (int.Parse(temp[4]) < 0) { user.dataSession.binaryWriter.Write(bytes, 0, count); user.dataSession.binaryWriter.Flush(); count = binaryReader.Read(bytes, 0, bytes.Length); } } else { StreamReader streamReader = new StreamReader(fs); while (streamReader.Peek() > -1) { user.dataSession.streamWriter.WriteLine(streamReader.ReadLine()); } } AddInfo("...]发送完毕!"); } finally { user.dataSession.Close(); fs.Close(); } } // 使用数据连接接收文件流(客户端发送上传文件功能) private void ReadFileByUserSession(User user, FileStream fs) { AddInfo("接收用户上传数据(文件流):[..."); try { if (user.isBinary) { byte[] bytes = new byte[1024]; BinaryWriter binaryWriter = new BinaryWriter(fs); int count = user.dataSession.binaryReader.Read(bytes, 0, bytes.Length); while (count > 0) { binaryWriter.Write(bytes, 0, count); binaryWriter.Flush(); count = user.dataSession.binaryReader.Read(bytes, 0, bytes.Length); } } else { StreamWriter streamWriter = new StreamWriter(fs); while (user.dataSession.streamReader.Peek() > -1) { streamWriter.Write(user.dataSession.streamReader.ReadLine()); streamWriter.Flush(); } } AddInfo("...]接收完毕"); } finally { user.dataSession.Close(); fs.Close(); } } private void label3_Click(object sender, EventArgs e) { } } }
C#中,异常处理机制用于处理在程序执行过程中可能发生的错误或异常情况。异常是一种表示程序执行期间出现问题的对象,它可以是系统定义的异常类型或自定义的异常类型。 异常处理的基本结构是使用try-catch块来捕获和处理异常。try块用于包含可能引发异常的代码,而catch块用于捕获和处理异常。 异常处理的基本语法如下: ```csharp try { // 可能引发异常的代码 } catch (ExceptionType1 ex) { // 处理特定类型的异常 } catch (ExceptionType2 ex) { // 处理另一种类型的异常 } finally { // 可选,无论是否发生异常,都会执行的代码 } ``` 在try块中,放置可能引发异常的代码。当异常发生时,会跳转到匹配的catch块进行处理。catch块可以根据需要捕获并处理特定类型的异常。多个catch块可以按顺序捕获不同类型的异常。 在catch块中,可以使用异常对象(如上面的ex)来访问有关异常的信息,如错误消息、堆栈跟踪等。在catch块中,可以针对不同的异常类型采取不同的处理方式,例如记录日志、发送警报或提供友好的错误提示。 finally块是可选的,包含无论是否发生异常都需要执行的代码。它通常用于释放资源或进行清理操作。 除了try-catch-finally结构,还可以使用throw语句手动引发异常。通过自定义异常类型,可以创建自己的异常类,并根据需要定义异常处理逻辑。 示例: ```csharp try { int result = Divide(10, 0); // 可能引发异常的方法调用 Console.WriteLine(result); } catch (DivideByZeroException ex) { Console.WriteLine("除零错误:" + ex.Message); } catch (Exception ex) { Console.WriteLine("其他错误:" + ex.Message); } finally { Console.WriteLine("无论是否发生异常,都会执行的代码"); } static int Divide(int x, int y) { if (y == 0) { throw new DivideByZeroException("除数不能为零"); } return x / y; } ``` 在上述示例中,我们尝试对10除以0,这会导致Divide方法引发DivideByZeroException异常。在catch块中,我们捕获并处理了这个特定类型的异常,并输出相应的错误消息。无论是否发生异常,finally块中的代码都会执行。 总结: C#中的异常处理机制通过try-catch-finally结构来捕获和处理异常。try块用于包含可能引发异常的代码,catch块用于捕获并处理特定类型的异常,finally块用于包含无论是否发生异常都需要执行的代码。通过使用自定义异常类型和throw语句,可以创建和引发自己的异常。合理的异常处理可以提高程序的健壮性和可靠性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值