Can There Be Private Extension Methods?

后端 未结 6 1179
Happy的楠姐
Happy的楠姐 2021-01-07 16:01

Let\'s say I have a need for a simple private helper method, and intuitively in the code it would make sense as an extension method. Is there any way to encapsulate that hel

6条回答
  •  悲&欢浪女
    2021-01-07 16:41

    This is taken from an example on microsoft msdn. Extesnion Methods must be defined in a static class. See how the Static class was defined in a different namespace and imported in. You can see example here http://msdn.microsoft.com/en-us/library/bb311042(v=vs.90).aspx

    namespace TestingEXtensions
    {
        using CustomExtensions;
        class Program
        {
            static void Main(string[] args)
            {
                var value = 0;
                Console.WriteLine(value.ToString()); //Test output
                value = value.GetNext(); 
                Console.WriteLine(value.ToString()); // see that it incremented
                Console.ReadLine();
            }
        }
    }
    
    namespace CustomExtensions 
    {
        public static class IntExtensions
        {
            public static int GetNext(this int i)
            {
                return i + 1;
            }
        }
    }
    

提交回复
热议问题