進哥的布拉格

Chin Gooole's Blog

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
// Extension Method --- Example ( Copyright from 進哥 in 博客園 )

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

static class Extension
{
    
/// <summary>
    
/// Extension Method: An extension method, Clone<T>, only copies the collection which saves value-type.
    
/// </summary>
    
/// <typeparam name="T"></typeparam>
    
/// <param name="list"></param>
    
/// <returns></returns>
    public static Collection<T> Clone<T>(this Collection<T> list) //where T : ICloneable
    {
        Collection
<T> newList = new Collection<T>();
        T data;
        
foreach (T el in list)
        {
            data 
= el;
            newList.Add(data);
        }

        
return newList;
    }

    
/// <summary>
    
/// Extension Method: An extension method for string type (from msdn)
    
/// </summary>
    
/// <param name="s"></param>
    
/// <returns></returns>
    public static int ToInt32(this string s)
    {
        
return Convert.ToInt32(s);
    } 


    
static void Main()
    {
        
// Test 1 -- Test the extension method of string
        string s = "10";
        
int integer = s.ToInt32();

        
// Test 2 -- Test the extension method of Collection<T> where T is value-type
        Collection<int> collection1 = new Collection<int>();
        collection1.Add(
32);
        collection1.Add(
40);
        
        Collection
<int> collection2 = collection1.Clone<int>();
        collection2[
0= 50;
        collection2[
1= 22;

        
// Test 3 -- Similar to Test 2, but test it in an object method
        MyClass objectMember = new MyClass();
        objectMember.TestObjectMethod(collection2);
    }
}

class MyClass
{
    
public void TestObjectMethod(Collection<int> list)
    {
        Collection
<int> collection3 = list.Clone<int>();
        collection3[
0= 99;
        collection3[
1= 12;
    }
}
posted on 2009-11-06 18:39  進哥  阅读(157)  评论(0编辑  收藏  举报