programing

방법 내 방법

goodcopy 2021. 1. 16. 10:36
반응형

방법 내 방법


재사용 가능한 코드로 C # 라이브러리를 만들고 메서드 내부에 메서드를 만들려고했습니다. 다음과 같은 방법이 있습니다.

public static void Method1()
{
   // Code
}

내가하고 싶은 것은 다음과 같습니다.

public static void Method1()
{
   public static void Method2()
   {
   }
   public static void Method3()
   {
   }
}

그런 다음 Method1.Method2또는을 선택할 수 있습니다 Method1.Method3. 분명히 컴파일러는 이것에 대해 만족하지 않으며 어떤 도움이라도 대단히 감사합니다. 감사.


이 답변은 C # 7이 나오기 전에 작성되었습니다. C # 7을 사용하면 로컬 메서드를 작성할 수 있습니다 .

아니, 당신은 할 수 없습니다. 당신은 할 수 중첩 클래스를 만들 :

public class ContainingClass
{
    public static class NestedClass
    {
        public static void Method2()
        {
        } 

        public static void Method3()
        {
        }
    }
}

그런 다음 전화합니다.

ContainingClass.NestedClass.Method2();

또는

ContainingClass.NestedClass.Method3();

나는 이것을 추천 하지 않을 것이다 . 일반적으로 공용 중첩 유형을 사용하는 것은 좋지 않습니다.

달성하려는 목표에 대해 자세히 말씀해 주시겠습니까? 더 나은 접근 방법이있을 수 있습니다.


중첩 된 메서드가 해당 메서드 내에서만 호출 할 수있는 메서드 (Delphi와 같이)를 의미하는 경우 대리자를 사용할 수 있습니다.

public static void Method1()
{
   var method2 = new Action(() => { /* action body */ } );
   var method3 = new Action(() => { /* action body */ } );

   //call them like normal methods
   method2();
   method3();

   //if you want an argument
   var actionWithArgument = new Action<int>(i => { Console.WriteLine(i); });
   actionWithArgument(5);

   //if you want to return something
   var function = new Func<int, int>(i => { return i++; });
   int test = function(6);
}

예, C# 7.0출시되면 로컬 기능 을 통해이를 수행 할 수 있습니다. 다음과 같은 메서드 내부에 메서드를 가질 수 있습니다.

public int GetName(int userId)
{
    int GetFamilyName(int id)
    {
        return User.FamilyName;
    }

    string firstName = User.FirstName;
    var fullName = firstName + GetFamilyName(userId);

    return fullName;
}

완전한 코드로 메서드 내에서 대리자를 정의하고 원하는 경우 호출 할 수 있습니다.

public class MyMethods
{
   public void Method1()
   {
     // defining your methods 

     Action method1 = new Action( () => 
      { 
         Console.WriteLine("I am method 1");
         Thread.Sleep(100);
         var b = 3.14;
         Console.WriteLine(b);
      }
     ); 

     Action<int> method2 = new Action<int>( a => 
      { 
         Console.WriteLine("I am method 2");
         Console.WriteLine(a);
      }
     ); 

     Func<int, bool> method3 = new Func<int, bool>( a => 
      { 
         Console.WriteLine("I am a function");
         return a > 10;
      }
     ); 


     // calling your methods

     method1.Invoke();
     method2.Invoke(10);
     method3.Invoke(5);

   }
}

클래스 내에서 외부에서 보이지 않는 중첩 클래스를 사용하고 다음과 같이 메서드를 호출하는 대안이 항상 있습니다.

public class SuperClass
{
    internal static class HelperClass
    {
      internal static void Method2() {}
    }

    public void Method1 ()
    {
      HelperClass.Method2();
    }

}

C # 7.0부터 다음과 같이 할 수 있습니다.

 public static void SlimShady()
 {
     void Hi([CallerMemberName] string name = null)
     {
         Console.WriteLine($"Hi! My name is {name}");
     }

     Hi();
 }

이것을 지역 기능 이라고합니다. 당신이 찾고 있던 바로 것입니다.

여기 에서 예를 들었지만 자세한 정보는 여기여기 에서 찾을 수 있습니다. .


수업을 사용하지 않는 이유는 무엇입니까?

public static class Helper
    {
        public static string MethodA()
        {
            return "A";
        }

        public static string MethodA()
        {
            return "A";
        }
    }

이제 다음을 통해 MethodA에 액세스 할 수 있습니다.

Helper.MethodA();

Older thread, but C# does have the concept of nested functions

    Func<int> getCalcFunction(int total, bool useAddition)
    {
        int overallValue = 0;
        if (useAddition)
        {
            Func<int> incrementer = new Func<int>(() =>
            {
                overallValue += total;
                return overallValue;
            });
            return incrementer;
        }
        else
        {
            Func<int> decrementer = new Func<int>(() =>
            {
                overallValue -= total;
                return overallValue;
            });
            return decrementer;
        }
    }
    private void CalcTotals()
    {
        Func<int> decrem = getCalcFunction(30, false);
        int a = decrem(); //result = -30
        a = decrem(); //result = -60

        Func<int> increm = getCalcFunction(30, true);
        int b = increm(); //result = 30
        b = increm(); //result = 60
    }

Your nearly there

public static void Method1()

should be

public static class Method1{}

Don't you want to use nested class instead?

That's said, you seem to not respect the Single Responsibility Principle because you want a single method do more than one thing at a time.


Why don't you just Run a method within another

public void M1() { DO STUFF }

public void M1() { DO STUFF M1(); }

ReferenceURL : https://stackoverflow.com/questions/8135050/method-within-a-method

반응형