附源代码+送分。通过编写自定义控件实例再论Delegate, Event Handling, anonymous method。
自定义控件的名称: SortableDropDownList, 继承DropDownList
不再过多解释什么是Delegate 和 Event Handling,要说的是,实战中,为什么要用它们,如何用它们提高开发效率,而不是为了用而用。
基于ASP.NET2.0的开发中,经常有二个场景使用Delegate:
1. Delegate + Event Handling
这个场景是经典Delegate使用场景,在这个场景中Delegate 和 Event Handling是联系在一起的。使用它的目的是将类更好的封装,定义这个类的事件,通过Delegate建立一个通道,当事件产生时可以传送给调用这个类的另外一个类。下面举例:
设计SortableDropDownList时,假设需要一个事件,这个事件是排序前激发,不返回任何EventArg.
首先定义事件: Public public event EventHandler SortingBegin; (这里没有定义delegate,因为EventHandler本身就是一个无返回事件数据的delegate,.Net已帮你定义好了。)
接着定义这个事件的方法:
public void OnSortingBegin()
{
if (SortingBegin != null)
{
SortingBegin(this, new EventArgs());
}
}
然后考虑什么时候调OnSortingBegin()这个方法以激发事件?自定义控件继承自dropdownlist,那么dropdownlist的PreRender事件是asp.net生命周期的最后一个事件,所以在这个事件激发的时候,dropdownlist所需做的都已经做完了,数据也已经绑定。所以就override这个事件。
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e); //做这个dropdown应该做的事,先。
OnSortingBegin(); //排序前调用事件方法
SortItems(); //排序,忽略这个,先。
}
现在,在某个使用这个控件的aspx页面,这个控件的属性里你就可以加上一个<..... SortingBegin = "OnSrotBegin"...>, 就像一个button,属性里你可以加 <...OnClick="...."> 一样。
然后假设需要定义另外一个事件,在排序完成时激发,返回排序前的itemList和排序后的itemList.
那么我首先定义这个事件返回数据类:public class SortingCompleteEventArgs : EventArgs (任何事件返回数据类都必须继承EventArgs类)
完整代码:
public class SortingCompleteEventArgs : EventArgs
{
private ListItem[] originalItems;
private ListItem[] sortedItems;
public ListItem[] OriginalItems
{
set { originalItems = value; }
get { return originalItems; }
}
public ListItem[] SortedItems
{
set { sortedItems = value; }
get { return sortedItems; }
}
public SortingCompleteEventArgs(int length)
{
originalItems = new ListItem[length];
sortedItems = new ListItem[length];
}
}
然后在自定义控件的类里加入如下代码,并做第一个事件代码的修改补充:
public delegate void SortingCompleteHandler(object sender, SortingCompleteEventArgs arg);
public event SortingCompleteHandler SortingComplete;
public void OnSortingComplete(SortingCompleteEventArgs arg)
{
if (SortingComplete != null)
{
SortingComplete(this, arg);
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
SortingCompleteEventArgs arg = new SortingCompleteEventArgs(this.Items.Count);
Items.CopyTo(arg.OriginalItems, 0);
OnSortingBegin(); //调用事件1的方法。
SortItems(); //排序方法,忽略,先。
Items.CopyTo(arg.SortedItems, 0);
OnSortingComplete(arg); //调用事件2的方法。
}
下面来说使用Delegate的第二场景 -- Delegate + 匿名方法
匿名方法是.Net 2.0后特有,作用是一小段代码,经常用,却不值得为它定义一个方法,那么就用匿名方法,
举个例--排序。
一个实体类Customer, 属性有Id(int),Name(string). 现在有List<Customer> customers已经取值完成。
现在来玩delegate + 匿名方法,
按照Name排序(升序):
customers.Sort(delegate(customer c1, customer c2) { return c1.Name.CompareTo(c2.Name) ;} );
降序:
customers.Sort(delegate(customer c1, customer c2) { return c2.Name.CompareTo(c1.Name) ;} );
按照Id排序:
customers.Sort(delegate(customer c1, customer c2) { return c1.Id > c2.Id ;} );
查找"Mike":
Customer c = customers.Find(delegate(Customer c3) { return c3.Name == "Mike"; });
查找所有Id >= 3:
List<Customer> customers2 = customers.FindAll(delegate(Customer c3) { return c3.Id >= 3; });
象不象.Net2.0 玩LINQ?
记住每一种技术细节的升级都是为了提高开发效率而诞生的,如果你不了解它,照猫画虎,为了时髦而用,技术升级对你来说就是负担。
相关推荐
CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)
一本不错的C#书,希望对您有帮助,本书目录: C# 3.0 Unleashed 1 Table of Contents 6 Introduction 30 Why This Book Is for You 31 Organization and Goals 32 Part 1 Learning C# Basics 36 1 Introducing the .NET Platform 38 What Is .NET? 38 The Common Language Runtime (CLR) 40 The .NET Framework Class Library (FCL) 43 C# and Other .NET Languages 45 The Common Type System (CTS) 46 The Common Language Specification (CLS) 46 Summary 46 2 Getting Started with C# and Visual Studio 2008 48 Writing a Simple C# Program 48 Creating a Visual Studio 2008 (VS2008) Project 52 Commenting Code 61 Identifiers and Keywords 64 Convention and Style 66 Variables and Types 67 Definite Assignment 73 Interacting with Programs 74 Summary 77 3 Writing C# Expressions and Statements 78 C# Operators 78 Statements 91 Blocks and Scope 92 Labels 92 Operator Precedence and Associativity 93 Selection and Looping Statements 94 Summary 106 4 Understanding Reference Types and Value Types 108 A Quick Introduction to Reference Types and Value Types 108 The Unified Type System 109 Reference Type and Value Type Memory Allocation 114 Reference Type and Value Type Assignment 117 More Differences Between Reference Types and Value Types 121 C# and .NET Framework Types 123 Nullable Types 131 Summary 132 5 Manipulating Strings 134 The C# String Type 134 The StringBuilder Class 151 Regular Expressions 153 Summary 158 6 Arrays and Enums 160 Arrays 160 The System.Array Class 166 Using Enum Types 168 The System.Enum struct 171 Summary 174 7 Debugging Applications with Visual Studio 2008 176 Stepping Through Code 176 Summary 188 Part 2 Object-Oriented Programming with C# 190 8 Designing Objects 192 Object Members 192 Instance and Static Members 193 Fields 194 Methods 195 Properties 196 Indexers 198 Reviewing Where Partial Types Fit In 199 Static Classes 200 The System.Object Class 201 Summary 204 9 Designing Object-Oriented Programs 206 Inheritance 207 Encapsulating Object Internals 213 Polymorphism 219 Summary 229 10 Coding Methods and Custom Operators 230 Methods 231 Overloading Methods 239 Overloading Operators 242 Conversions and Conversion Operator Overloads 247 Partial Methods 256 Extension Methods 257 Summary 259 11 Error and Exception Handling 260 Why Exception Handling? 261 Exception Handler Syntax: The Basic try/catch Block 261 Ensuring Resource Cleanup with finally Blocks 263 Handling Exceptions 264 Designing Your Own Exceptions 272 checked and unchecked Statements 274 Summary 277 12 Event-Based Programming with Delegates and Events 278 Exposing Delegates 279 Implementing Delegate Inference 285 Assigning Anonymous Methods 285 Coding Events 287 Summary 300 13 Naming and Organizing Types with Namespaces 302 Why Namespaces? 303 Namespace Directives 304 Creating Namespaces 307 Namespace Members 310 Scope and Visibility 311 Namespace Alias Qualifiers 312 Extern Namespaces Alias 313 Summary 315 14 Implementing Abstract Classes and Interfaces 316 Abstract Classes 317 Abstract Class and Interface Differences 319 Implementing Interfaces 320 Defining Interface Types 320 Implicit Implementation 322 Explicit Implementation 333 Interface Mapping 339 Interface Inheritance 341 Summary 344 Part 3 Applying Advanced C# Language Features 346 15 Managing Object Lifetime 348 Object Initialization 349 Object Initializers 355 Object Finalization 356 Automatic Memory Management 357 Proper Resource Cleanup 360 Interacting with the Garbage Collector 364 Summary 366 16 Declaring Attributes and Examining Code with Reflection 368 Using Attributes 369 Using Attribute Parameters 371 Attribute Targets 373 Creating Your Own Attributes 374 Using Reflection 378 Reflecting on Attributes 385 Summary 392 17 Parameterizing Type with Generics and Writing Iterators 394 Nongeneric Collections 395 Understanding the Benefits of Generics 395 Building Generic Types 401 Implementing Iterators 417 Summary 425 18 Using Lambda Expressions and Expression Trees 426 Lambda Expressions 427 Expression Trees 433 Summary 435 Part 4 Learning LINQ and .NET Data Access 436 19 Accessing Data with LINQ 438 LINQ to Objects 439 Querying Relational Data with LINQ to SQL 443 Standard Query Operators 456 Summary 468 20 Managing Data with ADO.NET 470 ADO.NET Architecture 470 Making Connections 474 Viewing Data 476 Manipulating Data 479 Calling Stored Procedures 481 Working with Disconnected Data 482 LINQ to DataSet 487 Summary 488 21 Manipulating XML Data 490 Streaming XML Data 491 Writing XML 491 Reading XML 494 Working with the XML DOM 495 Easier Manipulation with LINQ to XML 497 Summary 502 22 Creating Data Abstractions with the ADO.NET Entity Framework 504 An Overview of Entities 505 Starting the Entity Data Model in VS2008 505 Querying Entities with Entity SQL 509 Creating Custom Entities 511 Coding with LINQ to Entities 515 Summary 518 23 Working with Data in the Cloud with ADO.NET Data Services 520 Adding ADO.NET Data Services to Your Project 521 Accessing ADO.NET Data Services via HTTP URIs 522 Writing Code with the ADO.NET Data Services Client Library 528 Summary 533 Part 5 Building Desktop User Interfaces 534 24 Taking Console Applications to the Limit 536 Introducing the PasswordGenerator Console Application 537 Interacting with the User 537 Handling Command-Line Input 539 Adding Color and Positioning to Consoles 540 Summary 543 25 Writing Windows Forms Applications 544 Windows Forms Fundamentals 545 VS2008 Support for Windows Forms 548 Using Windows Forms Controls 557 MenuStrip, StatusStrip, and ToolStrip Controls 560 Data Grids and Data Binding 562 GDI+ Essentials 565 Additional Windows and Dialogs 568 Summary 574 26 Creating Windows Presentation Foundation (WPF) Applications 576 Just Enough XAML 577 Managing Layout 580 WPF Controls 589 Event Handling 602 Data Binding 603 Using Styles 607 Summary 609 Part 6 Designing Web User Interfaces 610 27 Building Web Applications with ASP.NET 612 The Web Application Model 612 Starting an ASP.NET Project with VS2008 615 A Lap Around an ASP.NET Page 617 Controls 622 State Management 625 Navigation 632 Theming a Site 638 Securing a Website 641 Data Binding 643 Summary 646 28 Adding Interactivity to Your Web Apps with ASP.NET AJAX 648 What Is AJAX? 648 Setting Up an ASP.NET AJAX Site 649 The AJAX Page Life Cycle 650 Loading Custom Script Libraries 652 ASP.NET AJAX Controls 654 Accessing Controls via JavaScript 657 Calling Web Services with ASP.NET AJAX 664 Summary 669 29 Crafting Rich Web Applications with Silverlight 670 What Makes Silverlight Tick? 670 Starting a Silverlight Project in VS2008 671 Handling Silverlight Events with C# 677 Playing Media 681 Animating UI Elements 684 Summary 686 Part 7 Communicating with .NET Technologies 688 30 Using .NET Network Communications Technologies 690 Implementing Sockets 690 Working with HTTP 698 Performing FTP File Transfers 700 Sending SMTP Mail 704 Summary 705 31 Building Windows Service Applications 708 Creating Windows Service Projects in VS2008 709 Coding Windows Services 712 Installing a Windows Service 717 Building a Controller to Communicate with a Windows Service 720 Summary 722 32 Remoting 724 Basic Remoting 724 Channels 735 Lifetime Management 738 Summary 741 33 Writing Traditional ASMX Web Services 742 Web Service Basics 742 Using Web Services 748 Summary 752 34 Creating Web and Services with WCF 754 Creating a WCF Application in VS2008 755 Creating a Web Service Contract 756 Implementing Web Service Logic 761 Configuring a Web Service 763 Consuming a Web Service 766 Summary 768 Part 8 Examining .NET Application Architecture and Design 770 35 Using the Visual Studio 2008 Class Designer 772 Visualizing Code 772 Building an Object Model with the Class Designer 778 Summary 783 36 Sampling Design Patterns in C# 784 Overview of Design Patterns 784 The Iterator Pattern 785 Implementing the Proxy Pattern 797 Implementing the Template Pattern 801 Summary 807 37 Building N-Tier/Layer Systems 808 Potential Drag-and-Drop Problems 808 Introducing N-Layer/N-Tier 810 N-Layer Architecture Examples 813 Summary 824 38 Automating Logic with Windows Workflow 826 Starting a Workflow Project 826 Building a Sequential Workflow 827 Building a State Workflow 832 Summary 842 Part 9 Surveying More of the .NET Framework Class Library 844 39 Managing Processes and Threads 846 .NET Process Support 847 Multithreading Overview 852 Thread Synchronization 855 Summary 858 40 Localizing and Globalization 860 Resource Files 860 Multiple Locales 872 Summary 880 41 Performing Interop (P/Invoke and COM) and Writing Unsafe Code 882 Unsafe Code 883 Platform Invoke 893 Communicating with COM from .NET 895 Exposing a .NET Component as a COM Component 898 Introduction to .NET Support for COM+ Services 900 Summary 905 42 Instrumenting Applications with System.Diagnostics Types 908 Simple Debugging 909 Conditional Debugging 910 Runtime Tracing 913 Making Assertions 915 Accessing Built-In Performance Counters 917 Implementing Timers 925 Building a Customized Performance Counter 926 Analyzing Performance with Sampling 937 Summary 946 Part 10 Deploying Code 948 43 Assemblies and Versioning 950 Inside Assemblies 950 Assembly Features 954 Configuration 956 Deployment 959 Summary 959 44 Securing Code 962 Code-Based Security 962 Role-Based Security 971 Security Utilities 973 Summary 974 45 Creating Visual Studio 2008 Setup Projects 976 Running the VS2008 Setup Project Wizard 976 Additional Setup Configuration 979 Summary 983 46 Deploying Desktop Applications 984 Deploying via ClickOnce 984 Configuring ClickOnce 986 Summary 988 47 Publishing Web Applications 990 The Anatomy of a Web Application 990 Web Server Setup 991 Virtual Directory Setup 992 Web Server Deployment 994 Publishing a Web App from VS2008 994 Summary 995 Part 11 Appendixes 996 A: Compiling Programs 998 Advanced 998 Assemblies 1000 B: Getting Help with the .NET Framework 1002 Read This Book 1002 Index 1003 .NET Framework Class Library Documentation 1003 Search Engines 1004 Favorite Websites 1004 Summary 1004
C#面试问题大全(最新整理)
C#面试问题大全(最新整理), C#面试问题大全,为准备找工作的同行们尽一份力!
C#高级特性解析(整合)
C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级特性解析C#高级
科技中介服务机构如何利用智能体提升技术需求挖掘与转化服务效率?.docx
科技中介服务机构如何利用智能体提升技术需求挖掘与转化服务效率?
高校技术转移办公室如何提升科技成果推介效率?.docx
高校技术转移办公室如何提升科技成果推介效率?


