Csharp/CSharp Tutorial/Class/Extension

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

Adding extension method for int

using System;
using System.Text;
using System.Reflection;
using System.Runtime.rupilerServices;
public static class MyExtensions
{
    public static void DisplayDefiningAssembly(this object obj)
    {
        Console.WriteLine(obj.GetType().Name);
        Console.WriteLine(Assembly.GetAssembly(obj.GetType()));
    }
    public static int ReverseDigits(this int i)
    {
        char[] digits = i.ToString().ToCharArray();
        Array.Reverse(digits);
        string newDigits = new string(digits);
        return int.Parse(newDigits);
    }
}
class Program
{
    static void Main(string[] args)
    {
        int myInt = 987;
        myInt.DisplayDefiningAssembly();
        Console.WriteLine("{0} is reversed to {1}", myInt, myInt.ReverseDigits());
        Console.ReadLine();
    }
}

Adding extension to Stream

using System.ruponentModel;
using System.IO;
using System.Net;

    public static class StreamUtilWithExtensions
    {
        const int BufferSize = 8192;
        public static void CopyTo(this Stream input,Stream output)
        {
            byte[] buffer = new byte[BufferSize];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
        public static byte[] ReadFully(this Stream input)
        {
            using (MemoryStream tempStream = new MemoryStream())
            {
                CopyTo(input, tempStream);
                if (tempStream.Length == tempStream.GetBuffer().Length)
                {
                    return tempStream.GetBuffer();
                }
                return tempStream.ToArray();
            }
        }
    }

    class MainClass
    {
        static void Main()
        {
            WebRequest request = WebRequest.Create("http://nfex.ru");
            using (WebResponse response = request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (FileStream output = File.Create("data.dat"))
            {
                responseStream.CopyTo(output);
            }
        }
    }

Adding reverse operation to string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    public static class ExtensionLibExtensions
    {
        public static string ReverseString(this string inputString)
        {
            return new string(inputString.ToCharArray().Reverse().ToArray());
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string sourceString = "this is a test";
            Console.WriteLine("String backwards: {0}", sourceString.ReverseString());
        }
    }

Add title case to string class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
    public static class ExtensionLibExtensions
    {
        public static string ToTitleCase(this string inputString, bool forceLower)
        {
            inputString = inputString.Trim();
            if (inputString == "")
            {
                return "";
            }
            if (forceLower)
            {
                inputString = inputString.ToLower();
            }
            string[] inputStringAsArray = inputString.Split(" ");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < inputStringAsArray.Length; i++)
            {
                if (inputStringAsArray[i].Length > 0)
                {
                    sb.AppendFormat("{0}{1} ",
                       inputStringAsArray[i].Substring(0, 1).ToUpper(),
                       inputStringAsArray[i].Substring(1));
                }
            }
            return sb.ToString(0, sb.Length - 1);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string sourceString = "this is a test";
            Console.WriteLine("String with title casing: {0}", sourceString.ToTitleCase(true));
        }
    }

conflicting extension methods

using System;
    public static class ExtensionMethods
    {
        public static string Substring(this string s, int startIndex, int endIndex)
        {
            if (startIndex >= 0 && startIndex <= endIndex && endIndex < s.Length)
                return s.Substring(startIndex, endIndex - startIndex);
            else
                return s;
        }
    }
    public class Tester{
        public static void Main()
        {
            string hello = "Hello";
            Console.WriteLine("hello.Substring(2, 3) = {0}", hello.Substring(2, 3));
        }
    }

extension method

using System;
    public static class ExtensionMethods
    {
        public static string Right(this string s, int n)
        {
            if (n < 0 || n > s.Length)
                return s;
            else
                return s.Substring(s.Length - n);
        }
    }
    public class Tester
    {
        public static void Main()
        {
            string hello = "Hello";
            Console.WriteLine("hello.Right(-1) = {0}", hello.Right(-1));
            Console.WriteLine("hello.Right(0) = {0}", hello.Right(0));
        }
    }

Extension Method On Null Reference

using System;
using System.ruponentModel;

    static class NullUtil
    {
        public static bool IsNull(this object x)
        {
            return x == null;
        }
    }
    class MainClass
    {
        static void Main()
        {
            object y = null;
            Console.WriteLine(y.IsNull());
            y = new object();
            Console.WriteLine(y.IsNull());
        }
    }