The definition of MSDN:
The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. ”
This means that you can extend the type int, String, DataTable, and so on, without having to modify or compile the code of the type itself.
As an example:
For example I'm on litedatatable (this type is the RAFY framework, you're going to do it as a DataTable type), directly on the Code analysis
public static class dataconvertextension { public static ConvertResult ToEntityList<T> (this litedatatable litedatatable) where T : EntityRepository { var convertResult = new ConvertResult (); var entitytype = typeof (T); var repo = rf . Resolveinstance<t> (); var Entitymeta = repo. entitymeta; var entiytype = Entitymeta.entitytype; var entity = rePo. New (); var list = repo. NewList (); var propertylist = entity. Propertiescontainer.getcompiledproperties (); Var columns = litedatatable.columns.select (E => e.columnname). ToList (); #region Determine if the litedatatable matches the Entity column to be converted var namelist = new list <string> ( var canconvert =); true; for (int i = 0; i < propertylist.count; i++) { &nBsp; namelist.add (PropertyList[i] . Name); } if (Propertylist.count == columns. Count) { for (int i = 0; i < propertylist.count; i++) { var columnName = columns[i]; if (!namelist.contains (columnName )) { canconvert = false; } } } #endregion if (Canconvert) { foreach (var row in Litedatatable.rows) { var entityitem = repo. New (); foreach (var property in propertylist) { Var propertyname = property. Name; if (columns. Contains (PropertyName)) { &nbSp; entityitem.loadproperty (Property, row[propertyname]); } } list. ADD (Entityitem); } } convertResult.Success = canConvert; convertResult.ResultList = list; return convertresult; } public class ConvertResult { public bool Success; public EntityList ResultList; } }
Look at the code above, the extension method specifies that the class must be a static class, Dataconvertextension is a static class, and all the methods contained in it must be static methods.
MSDN defines extension methods as follows: "extension methods are defined as static methods, but they are invoked through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. ”
That's the right thing to do when you call.
1 New litedatatable (); 2 3 L.toentitylist (entity);
C # Extension methods