Microsoft MVP성태의 닷넷 이야기
C# 7.1 185~187p 질문입니다. [링크 복사], [링크+제목 복사]
조회: 7252
글쓴 사람
꾸엉
홈페이지
첨부 파일
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Mathematics
{
    delegate int CalcDelegate(int x, int y);

    static int Add(int x, int y) { return x + y; }
    static int Subtract(int x, int y) { return x - y; }
    static int Multiply(int x, int y) { return x * y; }
    static int Divide(int x, int y) { return x / y; }

    CalcDelegate[] methods;

    public Mathematics()
    {
        methods = new CalcDelegate[] { Mathematics.Add,
            Mathematics.Subtract, Mathematics.Multiply, Mathematics.Divide };
    }

    public void Calculate(char opCode, int operand1, int operand2)
    {
        switch (opCode)
        {
            case '+':
                Console.WriteLine("+ : " + methods[0](operand1, operand2));
                break;

            case '-':
                Console.WriteLine("- : " + methods[1](operand1, operand2));
                break;

            case '*':
                Console.WriteLine("* : " + methods[2](operand1, operand2));
                break;

            case '/':
                Console.WriteLine("/ : " + methods[3](operand1, operand2));
                break;
        }
    }
}

namespace Study1
{

    class Program
    {
        delegate void WorkDelegate(char arg1, int arg2, int arg3);

        static void Main(string[] args)
        {
            Mathematics math = new Mathematics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
            work('-', 10, 5);
            work('*', 10, 5);
            work('/', 10, 5);
        }
    }
}



델리게이트를 공부하고 있는데요

왜 이번 예제에서는 Mathematics 클래스의 접근 제한자를 public으로 해서
namespace 밖에서 선언(?)을 한건가요?



그리고 static int Add(int x, int y) { return x + y; }
이 부분에서 static을 지우고 실행하면


        methods = new CalcDelegate[] { Mathematics.Add,
            Mathematics.Subtract, Mathematics.Multiply, Mathematics.Divide };

이 구문에서 Mathematics.Add 부분이 오류가 발생하던데

이 코드에서 static이 어떤 역할을 해주기에 static을 지우면 오류가 발생하는건가요?
ㅜㅜ static에 대한 개념을 잘 모르겠습니다..








[최초 등록일: ]
[최종 수정일: 10/29/2018]


비밀번호

댓글 작성자
 



2018-10-29 10시22분
namespace는 임의 관리 단위일 뿐 프로그램의 논리와는 상관이 없는 부분입니다. 그리고 static을 빼면 instance 멤버가 되기 때문에 그 앞에 클래스 이름을 붙일 수 없습니다. 따라서 "Mathematics.Add"라고 하면 안 되고 그냥 "Add"라고 해야 합니다.


정성태
2018-10-29 01시00분
[꾸엉] 감사합니다~!
[guest]

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5828김재영2/19/20233149장기적으로는 this 구문을 안쓰는게 맞을까요? [2]
5827lee2/18/20233064파이썬 설치 오류 질문입니다 [1]
5826Syong2/14/20233649Socket 관련 Leak (OverlappedAsyncResult, OverlappedData) 관련 문의 [7]파일 다운로드1
5825박성원2/14/20233223Listview 컨트롤의 화면 전환 시 갱신 속도 [1]
5823검은콩2/13/20233821catch(Exception ex)의 line번호를 쉽게 알 수 없는지요? [7]
5822김지우2/11/20233096책을 보면서 sync, async 이해가 되지 않는 부분이 있습니다. [5]파일 다운로드2
5821검은콩2/9/20233121Async 신뢰성과 소켓데이터 [4]
5820차가워2/8/20233181다른 프로세스 실행 후 포커스 가져오기 [3]
5819취준생2/7/20233333WPF 관련 실무가 궁금합니다. [3]
5818윤길2/7/20232782ObservableCollection 에서 INotifyPropertyChanged 구현해야하나요? [2]
5817흰털너부리2/7/20232920배포 시 winform 실행 콘솔로그 보는 방법 [1]
5816흰털너부리2/6/20232735.net core json array validation 질문 드립니다. [1]
5815김재영2/6/20232855종단간 암호화에 대해 시나리오인데 타당한 시나리오일까요? [2]
5814한예지 donator2/6/20233188decompile? [9]
5813김재영2/5/20233082openssl genrsa 2048시 키 생성이 다르게 됩니다. - 파일첨부 [4]파일 다운로드1
5812김재영2/5/20233364openssl genrsa 2048시 키 생성이 다르게 됩니다. [2]
5811치르바2/3/20233191MiniDumpWriteDump API로 덤프수집을 했는데요.. [3]
5810이건우1/31/20233292윈도우서비스를 통한 웹통신관련 질문입니다 [3]
5809이상훈1/31/20233734다채널 영상 디스플레이어 개발 관련 질문입니다. [3]
5808근우1/30/20233411WPF 에서 UserControl 과 ControlTemplate 의 차이점은 무엇인가요? [6]
5807궁금맨1/28/20234567C# 10 책에 나온 예제의 결과가 제 컴에서는 좀 달라서요. 이유가 궁금합니다. [1]
5806스레드1/25/20233079총정리 - 다양한 스레드들 [초안] [1]파일 다운로드1
5805어웨이트1/25/20232946Taskcontinuewith vs Async/Await [2]파일 다운로드1
5804나이많은...1/25/20232802MS의 Dependency Injection(DI)에 AddSingleton으로 등록된 객체의 Event 등록후 사용시 앱 종료시 별도로 Event를 해지해야 하나요? [2]
5803dssc...1/24/20233031드라이브 문자를 통해서 물리 디스크 명칭을 알아내고 싶습니다. [1]
5802모바일앱1/22/20232925XAMARINE vs Android Studio [7]
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...