[原创]深入理解C# 3.x的新特性(2):Extension Method - Part I

本文介绍了C#3.0中扩展方法的概念及其实现原理,通过对比JavaScript的Prototype机制,阐述了扩展方法如何在不修改原有类型的基础上为其添加新方法。
在C#3.0中,引入了一些列新的特性,比如: Implicitly typed local variable, Extension method,Lambda expression, Object initializer, Anonymous type, Implicitly typed array, Query expression, Expression tree. 个人觉得在这一系列新特性的,最具创新意义的还是Extension method,它从根本上解决了这样的问题:在保持现有Type原封不动的情况下对其进行扩展,你可以在对Type的定义不做任何变动的情况下,为之添加所需的方法成员。在继《深入理解C# 3.0的新特性(1): Anonymous Type 》之后,在这篇文章中,我将介绍我自己对Extension method这个新特性的理解。

一、Prototype in JavaScript

为了说明Extension method到底是为了解决怎样的问题,我首先给出一个类似的、大家都比较熟悉的应用:JavaScript 中的Prototype。

比如我们在JS通过function定义了一个Vector class,代表一个2维向量。

function  Vector (x,y)
{
     
this.x = x;
     
this.y = y;
}

现在我们需要在不改变Vector定义的前提下,为之添加相关的进行向量运算的Method。比如我们现在需要添加一个进行两个向量相加运算的adds方法。在JS中,我们很容易通过Prototype实现这一功能:

Vector.prototype.adds  =   function (v)
{
    
if(v instanceof Vector)
     
{
               
return new Vector(this.x+v.x, this.y + v.y);
      }

      
else
      
{
              alert(
"Invalid Vector object!");
      }

}

那么,通过添加上面的一段代码,我们完全可以把adds方法作为Vector的一个方法成员。现在我们可以这样的方式来写代码:

var  v  =   new  Vector ( 1 , 2 );
v
=  v.adds(v);
alert(
" x =  "   + v.x  +   " , y =  " + v.y);

Extension Method之于C# 3.0就如同Prototype之于JavaScript。 

二、如何在C# 2.0中解决Type的扩展性

我们一个完全一样的问题从弱类型、解释型的编程语言JavaScript迁移到C#这种强类型、编译型的语言上来。我们先看看在不能借助Extension Method这一新特性的C# 2.0中,我们是如何解决这一问题。

我们先来看看如何对一个Interface进行扩张。假设我们有如下的一个IVector interface的定义:

public   interface  IVector
{
        
double X getset; }
        
double Y getset; }
}

我们希望的是如何对这个Interface进行扩展,为之添加一个Adds Method执行向量相加的运算。我们唯一的解决方案就是直接在这个Interface中添加一个Adds成员:

public   interface  IVector
{
        
double X getset; }
        
double Y getset; }
        IVector Adds(IVector vector);
}

由于Interface和实现它的Type的紧密联系:所以实现了某个Interface的Type必须实现该Interface的所有方法。所以,我们添加了Adds Method,将导致所有实现它的Type的重新定义和编译,在很多情况下,这种代价我们是负担不起的:比如在系统的后期维护阶段,对系统的进行局部和全部的重新编译,将很有可以导致一个正常运行的系统崩溃。Interface的这种局限性在面向抽象设计和编程中应该得到充分的考虑,这也是我们在很多情况下宁愿使用Abstract Class的一个主要原因。

上面说到了对Interface的扩展,会出现必须实现Interface的Type进行改动的风险。我想有人会说,对Class尽心扩展就不会出现这样的情况了吧。不错,Class的继承性确保我们在Parent class添加的Public/Protect能被Child Class继承。比如:如果Vector是一个Super Class:

public   class  Vector 
    
{
        
private double _x;
        
private double _y;

        
public double X
        
{
            
get {return this._x;}
            
set this._x = value;}
        }


        
public double Y
        
{
            
get return this._y;}
            
set {this._y = value;}
        }

}

如果我们在Vector Class中添加一个Adds Method,所有的Child Class都不会受到影响。

但是在很多情况下,对于我们需要扩展的Interface或者是Type,我们是完全不能做任何改动。比如,某个Type定义在一个由第三方提供的Assembly中。在现有的情况下,对于这样的需求我们将无能为力。我们常用的方法就自己定义的Class去继承这个需要扩展,将需要添加的成员定义在我们自己定义的Class中,如果对于一个Sealed Class又该如何呢?即便不是Sealed Class,这作用方式也没有完成我们预定的要求:我们要求的是对这个不能变动的Type进行扩展,也就是所这个不能变动的Type的Instance具有我们添加的对象。

如果你在完全了解Extension Method的前提下听到这样的要求:我们要对一个Type或者Interface进行扩展,却不允许我们修改它。这个要求确实有点苛刻。但是,不能否认的是,这样需要在现实中的运用是相当广泛的。所以我说,Extension Method在所有提供的新特性中,是具有价值的一个。

三、C# 3.0中如何解决Type的扩展性

理解了我们的具体需要和现有编程语言的局限性后,我们来看看C# 3.0中是如何通过Extension Method解决这个问题的。

简单地说Extension Method是一个定义在Static Class的一个特殊的Static  Method。之所以说这个Static Method特别,是因为Extension Method不但能按照Static Method的语法进行调用,还能按照Instance Method的语法进行调用。

我们还是先来看例子,首先是我们需要进行扩展的Vector Type的定义:

public   class  Vector 
{
        
private double _x;
        
private double _y;

        
public double X
        
{
            
get {return this._x;}
            
set this._x = value;}
        }


        
public double Y
        
{
            
get return this._y;}
            
set {this._y = value;}
        }

}

在不对Vector Class的定义进行更新的前提下,我们把需要添加的Adds方法定义在一个Static Class中:

public   static   class  Extension
    
{    
        
public static Vector Adds(this Vector p,Vector p1)
        
{
            
return new Vector { X = p.X + p1.X, Y = p.Y + p1.Y };
        }

}

这个Extension Method:Adds是一个Static方法。和一般的Static方法不同的是:在第一个参数前添加了一个this 关键字。这是在C# 3.0中定义Extension Method而引入的关键字。添加了这样一个关键字就意味着在调用该方法的时候这个标记有this的参数可以前置,从而允许我们向调用一般Instance Method的方式来调用这个Static Method。比如:

class  Program
    
{
        
static void Main(string[] args)
        
{
            var v 
= new Vector { X = 1, Y = 2 };
            v 
= v.Adds(v);
            Console.WriteLine(
"v.X = {0} and v.Y = {1}", v.X, v.Y);
        }

}

注:this关键字只能用于标记第一个参数。 

通过上面的介绍,我们知道在C# 3.0如何通过定义Extension Method在不对Type作任何修改的前提下对Type进行扩展。至于Extension Method的本质:C# Compiler在编译Extension Method时会做怎样处理;在最终被编译成的Assembly中相关的IL具有怎样的特征;Extension Method的优先级,如果有兴趣,可以参考《[原创]深入理解C# 3.0的新特性(2):Extension Method - Part II》,此外在第二部分中,我会给出一个完整的Sample:通过Extension Method定义一个形如LINQ中常见的Operator,完成基于LINQ的查询功能。 

C# 3.x相关内容:
[原创]深入理解C# 3.x的新特性(1):Anonymous Type
[原创]深入理解C# 3.x的新特性(2):Extension Method - Part I
[原创]深入理解C# 3.x的新特性(2):Extension Method - Part II
[原创]深入理解C# 3.x的新特性(3):从Delegate、Anonymous Method到Lambda Expression
[原创]深入理解C# 3.x的新特性(4):Automatically Implemented Property
[原创]深入理解C# 3.x的新特性(5):Object Initializer 和 Collection Initializer

//============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\001 NX Model\000 NX Custom Development\ART_NX_C\ArkTech\Modeling_Custom.cs // // This file was generated by the NX Block UI Styler // Created by: jzk24 // Version: NX 2406 // Date: 08-30-2025 (Format: mm-dd-yyyy) // Time: 12:07 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C# source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ //These imports are needed for the following template code //------------------------------------------------------------------------------ using NXOpen; using NXOpen.BlockStyler; using NXOpen.UF; using NXOpen.Utilities; using System; using static NXOpen.BodyDes.OnestepUnformBuilder; using OnestepPart = NXOpen.BodyDes.OnestepUnformBuilder.Part; // 为另一个 Part 定义别名 using Part = NXOpen.Part; //------------------------------------------------------------------------------ //Represents Block Styler application class //------------------------------------------------------------------------------ public class Modeling_Custom { //class members private static Session theSession = null; private static UI theUI = null; private string theDlxFileName; private NXOpen.BlockStyler.BlockDialog theDialog; private NXOpen.BlockStyler.Group group1;// Block type: Group private NXOpen.BlockStyler.Enumeration enum0;// Block type: Enumeration private NXOpen.BlockStyler.StringBlock string0;// Block type: String private NXOpen.BlockStyler.StringBlock string01;// Block type: String private NXOpen.BlockStyler.Group group;// Block type: Group private NXOpen.BlockStyler.StringBlock string02;// Block type: String private Part workPart; //------------------------------------------------------------------------------ //Constructor for NX Styler class //------------------------------------------------------------------------------ public Modeling_Custom() { try { theSession = Session.GetSession(); theUI = UI.GetUI(); theDlxFileName = "Modeling_Custom.dlx"; theDialog = theUI.CreateDialog(theDlxFileName); theDialog.AddApplyHandler(new NXOpen.BlockStyler.BlockDialog.Apply(apply_cb)); theDialog.AddOkHandler(new NXOpen.BlockStyler.BlockDialog.Ok(ok_cb)); theDialog.AddUpdateHandler(new NXOpen.BlockStyler.BlockDialog.Update(update_cb)); theDialog.AddInitializeHandler(new NXOpen.BlockStyler.BlockDialog.Initialize(initialize_cb)); theDialog.AddDialogShownHandler(new NXOpen.BlockStyler.BlockDialog.DialogShown(dialogShown_cb)); } catch (Exception ex) { //---- Enter your exception handling code here ----- throw ex; } } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. Journal Replay // // 1) Replay this file through Tool->Journal->Play Menu. // // 2. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ public static void Main() { Modeling_Custom theModeling_Custom = null; try { theModeling_Custom = new Modeling_Custom(); // The following method shows the dialog immediately theModeling_Custom.Launch(); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } finally { if (theModeling_Custom != null) theModeling_Custom.Dispose(); theModeling_Custom = null; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return Value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ public static int GetUnloadOption(string arg) { //return System.Convert.ToInt32(Session.LibraryUnloadOption.Explicitly); return System.Convert.ToInt32(Session.LibraryUnloadOption.Immediately); // return System.Convert.ToInt32(Session.LibraryUnloadOption.AtTermination); } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ public static void UnloadLibrary(string arg) { try { //---- Enter your code here ----- } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //This method launches the dialog to screen //------------------------------------------------------------------------------ public NXOpen.BlockStyler.BlockDialog.DialogResponse Launch() { NXOpen.BlockStyler.BlockDialog.DialogResponse dialogResponse = NXOpen.BlockStyler.BlockDialog.DialogResponse.Invalid; try { dialogResponse = theDialog.Launch(); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return dialogResponse; } //------------------------------------------------------------------------------ //Method Name: Dispose //------------------------------------------------------------------------------ public void Dispose() { if (theDialog != null) { theDialog.Dispose(); theDialog = null; } } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ public void initialize_cb() { try { group1 = (NXOpen.BlockStyler.Group)theDialog.TopBlock.FindBlock("group1"); enum0 = (NXOpen.BlockStyler.Enumeration)theDialog.TopBlock.FindBlock("enum0"); string0 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string0"); string01 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string01"); group = (NXOpen.BlockStyler.Group)theDialog.TopBlock.FindBlock("group"); string02 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string02"); //------------------------------------------------------------------------------ //Registration of StringBlock specific callbacks //------------------------------------------------------------------------------ //string0.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //string01.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //string02.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //------------------------------------------------------------------------------ } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any Value set //here will take precedence and dialog will be launched showing that Value. //------------------------------------------------------------------------------ public void dialogShown_cb() { try { //---- Enter your callback code here ----- } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ public int apply_cb() { int errorCode = 0; try { workPart = theSession.Parts.Work; if (workPart == null) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "没有打开的零件文件"); return errorCode; } // 1. 将enum0的值赋予"型号"属性 string modelType = enum0.ValueAsString; SetPartProperty(workPart, "型号", modelType); // 2. 将string0的值赋予"DB_PART_NO"属性 string partNo = string0.Value; if (!string.IsNullOrEmpty(partNo)) { SetPartProperty(workPart, "DB_PART_NO", partNo); } else { theUI.NXMessageBox.Show("警告", NXMessageBox.DialogType.Warning, "零件编号不能为空"); } // 3. 将string01的值赋予"DB_PART_NAME"属性 string partName = string01.Value; SetPartProperty(workPart, "DB_PART_NAME", partName); // 4. 将string02的值设置为与string0相同 string02.Value = string0.Value; theUI.NXMessageBox.Show("成功", NXMessageBox.DialogType.Information, "属性已成功更新"); } catch (Exception ex) { //---- Enter your exception handling code here ----- errorCode = 1; theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return errorCode; } private void SetPartProperty(Part workPart, string propertyName, string propertyValue) { try { // 检查部件是否为空 if (workPart == null) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "部件为空"); return; } // 使用 UFUN 检查部件是否可写 if (!IsPartWriteable(workPart)) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "部件不可写"); return; } // 使用 UFUN 设置属性 UFSession ufSession = UFSession.GetUFSession(); int result= ufSession.Attr.SetStringUserAttribute( workPart.Tag, propertyName, 0, propertyValue, UFAttr.Equals); if (result !=0) { // 处理错误 theUI.NXMessageBox.Show("属性设置警告", NXMessageBox.DialogType.Warning, $"属性操作返回代码: {result}"); } } catch (Exception ex) { // 异常处理 theUI.NXMessageBox.Show("设置属性错误", NXMessageBox.DialogType.Error, $"无法设置属性 '{propertyName}':{ex.Message}"); // 注意:这里不应该抛出 NotImplementedException } } // 添加检查部件可写状态的方法 private bool IsPartWriteable(Part part) { try { UFSession ufSession = UFSession.GetUFSession(); int writeStatus; object value = ufSession.Part.AskWriteStatus(part.Tag, out IsPartWriteable); // writeStatus 值为 0 表示部件可写 return IsPartWriteable; } catch { return false; } } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ public int update_cb(NXOpen.BlockStyler.UIBlock block) { try { if (block == enum0) { string02.Value = string0.Value; } else if (block == string0) { //---------Enter your code here----------- } else if (block == string01) { //---------Enter your code here----------- } else if (block == string02) { //---------Enter your code here----------- } } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ public int ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); if (errorCode == 0) { theDialog.Dispose(); } } catch (Exception ex) { //---- Enter your exception handling code here ----- errorCode = 1; theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return errorCode; } //------------------------------------------------------------------------------ //StringBlock specific callbacks //------------------------------------------------------------------------------ //public int KeystrokeCallback(NXOpen.BlockStyler.StringBlock string_block, string uncommitted_value) //{ //} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ public PropertyList GetBlockProperties(string blockID) { PropertyList plist = null; try { plist = theDialog.GetBlockProperties(blockID); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return plist; } } 发现以下错误:CS1503参数5:无法从"方法组"转换为"bool" CS1061"UFPart"未包含"AskWriteStatus"的定义,并且找不到可接受第一个"UFPart"类型参数的可访问扩展方法"AskWriteStatus"(是否缺少using指令或程序集引用?) CS1657"IsPartWriteable"是一个"方法组",无法用作 ref或cput值 CS0428无法将方法组"IsPartWriteable"转换为非委托类型"bcol"。是否希望调用此方法? CS0168 声明了变量"writeStatus",但从未使用过 CS0168 声明了变量"ex",但从未使用过 CS0168 声明了变量"ex",但从未使用过 CS0168 声明了变量"ex",但从未使用过,请更改
最新发布
09-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值