Extend an existing class C #

To extend an existing class method

using System;

namespace PureCSharpTest
{   
    public class Rubbish
    {
        public void Say()
        {
            Console.Write("Hello");
        }
    }
    public static class RubbishExtensions
    {
        public static void Say(this Rubbish argRubbish, string argString)
        {
            Console.Write(argString);
        }
        public static void Hello(this Rubbish rubbish)
        {
            Console.WriteLine("extension hello");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Rubbish theRubbish = new Rubbish();
            theRubbish.Say("Hey");
            theRubbish.Hello();
            theRubbish.OtherFileTestHello();
            Console.ReadKey(false);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace PureCSharpTest
{
    public static class extensionOtherFileTest
    {
        public static void OtherFileTestHello(this Rubbish rubbish)
        {
            Console.WriteLine("other file extension hello");
        }
    }
}

Visible, this method is extended, as long as access to take into account, it can be polymorphic and extension methods, and only you can at the same namespace

Published 19 original articles · won praise 2 · Views 5159

Guess you like

Origin blog.csdn.net/gunjiu4462/article/details/103050429