ASP.NET Tutorial/Collections/Generics
Содержание
- 1 A generic Stack class (C#)
- 2 A generic Stack class using integers (C#)
- 3 A generic Stack class using integers (VB)
- 4 A generic Stack class (VB)
- 5 Creating a list of Person objects using generics (C#)
- 6 Creating a list of Person objects using generics (VB)
- 7 Generic collections
- 8 Test Generic Collections
A generic Stack class (C#)
<source lang="csharp">
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) { Stack<string> myStack = new Stack<string>(); myStack.Push("A"); myStack.Push("B"); myStack.Push("C"); Array myArray; myArray = myStack.ToArray(); foreach (string item in myArray) { Label1.Text += item + "
"; } }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="Label1"></asp:Label>
</form>
</body> </html></source>
A generic Stack class using integers (C#)
<source lang="csharp">
<%@ Page Language="VB" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) { Stack<int> myStack = new Stack<int>(); myStack.Push(5); myStack.Push(3); myStack.Push(10); Array myArray; myArray = myStack.ToArray(); int x = 0; foreach (int item in myArray) { x += item; } Label1.Text = x.ToString(); }
</script></source>
A generic Stack class using integers (VB)
<source lang="csharp">
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myStack As New Stack(Of Integer) myStack.Push(5) myStack.Push(3) myStack.Push(10) Dim myArray As Array myArray = myStack.ToArray() Dim x As Integer = 0 For Each item As Integer In myArray x += item Next Label1.Text = x.ToString() End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="Label1"></asp:Label>
</form>
</body> </html></source>
A generic Stack class (VB)
<source lang="csharp">
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myStack As New System.Collections.Generic.Stack(Of String) myStack.Push("A") myStack.Push("B") myStack.Push("C") Dim myArray As Array myArray = myStack.ToArray() For Each item As String In myArray Label1.Text += item & "
" Next End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="Label1"></asp:Label>
</form>
</body> </html></source>
Creating a list of Person objects using generics (C#)
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.cs using System; using System.Collections; using System.Collections.Generic; public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Person scott = new Person("A", "D"); Person bill = new Person("B", "E"); Person srini = new Person("C", "F"); List<Person> people = new List<Person>(); people.Add(scott); people.Add(bill); people.Add(srini); foreach (Person p in people) { Response.Write(p.FullName + "
"); } for (int i = 0; i < people.Count; i++) { Response.Write(people[i].FullName + "
"); } }
} public class Person : IComparable {
string FirstName; string LastName; public Person(string first, string last) { FirstName = first; LastName = last; } public string FullName { get { return FirstName + " " + LastName; } } int IComparable.rupareTo(object obj) { Person p2 = obj as Person; if (p2 == null) throw new ArgumentException("Object is not a Person!"); int lastNameResult = this.LastName.rupareTo(p2.LastName); if (lastNameResult == 0) { int firstNameResult = this.FirstName.rupareTo(p2.FirstName); return firstNameResult; } else { return lastNameResult; } }
}</source>
Creating a list of Person objects using generics (VB)
<source lang="csharp">
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.vb Imports System Imports System.Collections Imports System.Collections.Generic Imports Microsoft.VisualBasic Public Class Person
Implements IComparable Dim FirstName As String Dim LastName As String Public Sub New(ByVal First As String, ByVal Last As String) FirstName = First LastName = Last End Sub Public ReadOnly Property FullName() As String Get Return FirstName & " " & LastName End Get End Property Public Function CompareTo(ByVal obj As Object) _ As Integer Implements IComparable.rupareTo If Not TypeOf (obj) Is Person Then Throw New ArgumentException("Object is not a Person!") End If Dim p2 As Person = CType(obj, Person) Dim lastNameResult As Integer = Me.LastName.rupareTo(p2.LastName) If lastNameResult = 0 Then Dim firstNameResult As Integer = Me.FirstName.rupareTo(p2.FirstName) Return firstNameResult Else Return lastNameResult End If End Function
End Class Partial Class _Default
Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim scott As New Person("A", "F") Dim bill As New Person("B", "E") Dim srini As New Person("C", "D") Dim people As New List(Of Person) people.Add(scott) people.Add(bill) people.Add(srini) For Each p As Person In people Response.Write(p.FullName & "
") Next For i As Integer = 0 To people.Count - 1 Response.Write(people(i).FullName & "
") Next End Sub
End Class</source>
Generic collections
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TestGenericCollections" Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<title>Test Generic Collections</title>
</head> <body>
<form id="form1" runat="server">
Test Generic Collections
This is a tester for our generic collection class. <asp:ListBox ID="lboxCustomers" runat="server" />
Retrieved Customer via index: <asp:Label ID="labCustomer" runat="server" />
<asp:CheckBox ID="chkValidCustomer" runat="server" Text="Is Valid?" /> <asp:ListBox ID="lboxProducts" runat="server" />
Retrieved Product via index: <asp:Label ID="labProduct" runat="server" />
<asp:CheckBox ID="chkValidProducer" runat="server" Text="Is Valid?" />
</form>
</body> </html>
File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using System.Collections.ObjectModel;
public class Product: AbstractEntity {
private string _name; private double _price; public Product(string id, string name, double price) : base(id) { _name = name; _price = price; } public string Name { get { return _name; } set { _name = value; } } public double Price { get { return _price; } set { _price = value; } } public override string ToString() { return Id + "," + Name + "," + Price; } public override bool IsValid { get { if (Id.Length > 0 && Name.Length > 0) return true; else return false; } }
} public class EntityCollection<T> : Collection<T> where T : AbstractEntity {
public T FindById(string id) { foreach (T entity in this.Items) { if (entity.Id == id) return entity; } return null; }
public bool IsValid() { bool valid = true; foreach (T entity in this.Items) { if (!entity.IsValid) valid = false; } return valid; }
} public partial class TestGenericCollections : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Customer c1 = new Customer("1", "A", "H", "123-4567"); Customer c2 = new Customer("2", "B", "G", "456-1267"); Customer c3 = new Customer("3", "C", "F", "564-7823"); Customer c4 = new Customer("4", "D", "E", "253-6383"); EntityCollection<Customer> customers = new EntityCollection<Customer>(); customers.Add(c1); customers.Add(c2); customers.Add(c3); customers.Add(c4); lboxCustomers.DataSource = customers; lboxCustomers.DataBind(); labCustomer.Text = customers[2].Name; chkValidCustomer.Checked = customers.IsValid(); Product p1 = new Product("1", "ProductOne", 24.00); Product p2 = new Product("2", "", 59.00); EntityCollection<Product> products = new EntityCollection<Product>(); products.Add(p1); products.Add(p2); lboxProducts.DataSource = products; lboxProducts.DataBind(); labProduct.Text = products[0].Name; chkValidProducer.Checked = products.IsValid(); }
} public abstract class AbstractEntity {
private string _id; public AbstractEntity(string id) { _id = id; }
public string Id { get { return _id; } set { _id = value; } }
public abstract bool IsValid { get; }
} public class Customer: AbstractEntity {
private string _firstName; private string _lastName; private string _phone; public Customer(string id, string firstName, string lastName, string phone): base(id) { _firstName = firstName; _lastName = lastName; _phone = phone; }
public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public string Name { get { return LastName + ", " + FirstName; } } public override bool IsValid { get { if (Id.Length > 0 && LastName.Length > 0) return true; else return false; } } public override string ToString() { return Id + "," + Name + "," + Phone; }
}</source>