[笔记] C# 3.0 新特性[2]-Understanding Extension Methods

本文详细介绍了C# 3.0中的扩展方法特性,解释了如何利用静态类和静态方法为已有的类型添加新功能。文章通过具体示例展示了扩展方法的定义与调用方式,并探讨了其实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

None.gifnamespace net30netfeature.extendMethod
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
using System;
InBlock.gif
InBlock.gif    
static class MyExtensions
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// This method allows any object to display the assembly
InBlock.gif        
// it is defined in.
InBlock.gif
        public static void DisplayDefiningAssembly(this object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"{0} lives here:\n\t->{1}\n", obj.GetType().Name,
InBlock.gif            System.Reflection.Assembly.GetAssembly(obj.GetType()));
ExpandedSubBlockEnd.gif        }

InBlock.gif        
// This method allows any integer to reverse its digits.
InBlock.gif        
// For example, 56 would return 65.
InBlock.gif
        public static int ReverseDigits(this int i)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Translate int into a string, and then
InBlock.gif            
// get all the characters.
InBlock.gif
            char[] digits = i.ToString().ToCharArray();
InBlock.gif            
// Now reverse items in the array.
InBlock.gif
            Array.Reverse(digits);
InBlock.gif            
// Put back into string.
InBlock.gif
            string newDigits = new string(digits);
InBlock.gif            
// Finally, return the modified string back as an int.
InBlock.gif
            return int.Parse(newDigits);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
// Every Int32 now has a Foo() methoddot.gif
InBlock.gif
//        [System.Runtime.CompilerServices.Extension]
InBlock.gif
        internal static void Foo(this int i)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{ Console.WriteLine("{0} called the Foo() method.", i); }
InBlock.gif        
// dot.gifwhich has been overloaded to take a string!
InBlock.gif
        internal static void Foo(this int i, string msg)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{ Console.WriteLine("{0} called Foo() and told me: {1}", i, msg); }
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

None.gif
None.gif
namespace net30netfeature
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
using System;
InBlock.gif    
//Importing Types That Define Extension Methods
InBlock.gif
    using net30netfeature.extendMethod;
InBlock.gif    
InBlock.gif    
public class Extentionmethod
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//*
InBlock.gif         *就你所知,一个类型一但被定义编译后,就定型了。要想添加新功能方法只能通过继承,修改原代码,或通过System.Reflection.Emit
InBlock.gif         *进行反射注入进行动态编译。
InBlock.gif         * C# 3.0的扩展方法特性使这一需求成为了可能,扩展方法可以扩展已经存在的编译类型,使之添加新的成员,
InBlock.gif         * 而不用更新原有的类型。
InBlock.gif         * 这是非常有用的,当你需要注入新的功能到已经存在的类型中时,使用扩展方法,你可以添加新的功能到已经编译的类型中,
InBlock.gif         * 来提供一个幻影,如同已经存在的类型具有这个功能方法。
InBlock.gif         * 定义扩展方法时有三个限制:
InBlock.gif         * 1)方法必须定义在静态类中,每个扩展方法也必须是静态方法。
InBlock.gif         * 2)扩展方法的第一个参数必须用this关键定进行标识。
InBlock.gif         * 3)扩展方法可以通过相应的实例方式或通过静态类方式进行调用。        
ExpandedSubBlockEnd.gif         
*/

ExpandedSubBlockEnd.gif    }
    
InBlock.gif    
public static class TesterUtilClass
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public static void Test()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Test2();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif         
/**//// <summary>
InBlock.gif        
/// Invoking Extension Methods from an Instance Level
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public static void Test1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"***** Fun with Extension Methods *****\n");
InBlock.gif            
// The int has assumed a new identity!
InBlock.gif
            int myInt = 12345678;
InBlock.gif            myInt.DisplayDefiningAssembly();
InBlock.gif            
// So has the DataSet!
InBlock.gif
            System.Data.DataSet d = new System.Data.DataSet();
InBlock.gif            d.DisplayDefiningAssembly();
InBlock.gif            
// And the SoundPlayer!
InBlock.gif
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
InBlock.gif            sp.DisplayDefiningAssembly();
InBlock.gif            
// Use new integer functionality.
InBlock.gif
            Console.WriteLine("Value of myInt: {0}", myInt);
InBlock.gif            Console.WriteLine(
"Reversed digits of myInt: {0}", myInt.ReverseDigits());
InBlock.gif            myInt.Foo();
InBlock.gif            myInt.Foo(
"Ints that Foo? Who would have thought it!");
InBlock.gif            
// Error! Booleans don't have the Foo() method!
InBlock.gif
            bool b2 = true;
InBlock.gif            
// b2.Foo();
ExpandedSubBlockEnd.gif
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Invoking Extension Methods Statically
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public static void Test2()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
/**//*
InBlock.gif             * 回忆一下扩展方法的第一个参数被标记为this关键字,其后跟随着方法被应用的类型,如果我们看一下
InBlock.gif             * 这个背后发生了什么,可以用 ildasm.exe or Lutz Roeder’s Reflector来进行查看,我们会发现,编译器
InBlock.gif             * 把实例的扩展方法的调用转换成静态方法的调用。和如下的方法的调用类似。
ExpandedSubBlockEnd.gif             
*/

InBlock.gif            Console.WriteLine(
"***** Fun with Extension Methods *****\n");
InBlock.gif            
int myInt = 12345678;
InBlock.gif            MyExtensions.DisplayDefiningAssembly(myInt);
InBlock.gif            System.Data.DataSet d 
= new System.Data.DataSet();
InBlock.gif            MyExtensions.DisplayDefiningAssembly(d);
InBlock.gif            System.Media.SoundPlayer sp 
= new System.Media.SoundPlayer();
InBlock.gif            MyExtensions.DisplayDefiningAssembly(sp);
InBlock.gif            Console.WriteLine(
"Value of myInt: {0}", myInt);
InBlock.gif            Console.WriteLine(
"Reversed digits of myInt: {0}",
InBlock.gif            MyExtensions.ReverseDigits(myInt));
InBlock.gif            MyExtensions.Foo(myInt);
InBlock.gif            MyExtensions.Foo(myInt, 
"Ints that Foo? Who would have thought it!");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/snowball/archive/2008/02/20/1074789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值