Csharp/C Sharp/LINQ/Extension Method

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Add Extension method

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
public static class Extensions {
    public static string SpaceToUnderscore(this string source) {
        char[] cArray = source.ToCharArray();
        string result = null;
        foreach (char c in cArray) {
            if (Char.IsWhiteSpace(c))
                result += "_";
            else
                result += c;
        }
        return result;
    }
}
class Program {
    static void Main(string[] args) {
        string s = "This is a test";
        Console.WriteLine(s.SpaceToUnderscore());
    }
}


Extension method for integer

 

using System;
static class MainClass {
    public static int ConvertToBase(this int i, int baseToConvertTo) {
        if (baseToConvertTo < 2 || baseToConvertTo > 10)
            throw new ArgumentException("Value cannot be converted to base " + baseToConvertTo.ToString());
        int result = 0;
        int iterations = 0;
        do {
            int nextDigit = i % baseToConvertTo;
            result += nextDigit * (int)Math.Pow(10, iterations);
            iterations++;
            i /= baseToConvertTo;
        }
        while (i != 0);
        return result;
    }
    static void Main() {
        try {
            int x = 591;
            for (int i = 2; i <= 10; i++) {
                Console.WriteLine("{0} in base {1} is {2}", x, i, x.ConvertToBase(i));
            }
        } catch (Exception ex) {
            Console.WriteLine("Exception: {0}", ex.Message);
        }
    }
}


Extension Methods Discoverability

 
using System;
class Class1 {
}
class Class2 {
    public void Method1(string s) {
        Console.WriteLine("Class2.Method1");
    }
}
class Class3 {
    public void Method1(object o) {
        Console.WriteLine("Class3.Method1");
    }
}
class Class4 {
    public void Method1(int i) {
        Console.WriteLine("Class4.Method1");
    }
}
static class Extensions {
    static public void Method1(this object o, int i) {
        Console.WriteLine("Extensions.Method1");
    }
    static void Main() {
        new Class1().Method1(12); // Extensions.Method1 is called
        new Class2().Method1(12); // Extensions.Method1 is called
        new Class3().Method1(12); // Class3.Method1 is called
        new Class4().Method1(12); // Class4.Method1 is called
    }
}


Object Initializer

 
using System;
using System.Collections.Generic;
using System.Diagnostics;
class MyPC {
    public Int32 Id { get; set; }
    public Int64 Memory { get; set; }
    public String Name { get; set; }
}
public class MainClass {
    static void Main(string[] args) {
        var processes = new List<MyPC>();
        foreach (var process in Process.GetProcesses()) {
            processes.Add(new MyPC {
                Id = process.Id,
                Name = process.ProcessName, 
                Memory = process.WorkingSet64
            });
        }
    }
}