Microsoft MVP성태의 닷넷 이야기
글쓴 사람
guest
홈페이지
첨부 파일
 

 public partial class Form1 : Form
 {
        
        public Form1()
        {
            InitializeComponent();
        }
                                     //this Error
        public static Image resizeImage(this Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }


질문>
 resizeImage(this Image imgToResize, Size size)에서 this를 빼면 에러가
위 에러가 안납니다

그런데 this를 써야 되는 경우가 혹시 있나요?








[최초 등록일: ]
[최종 수정일: 4/6/2023]


비밀번호

댓글 작성자
 



2023-04-06 08시41분
질문의 내용은 C# 3.0에 나온 "확장 메서드"를 기본적으로 모르기 때문에 나오는 것입니다. 그걸 공부하신 다음에,

Extension Methods (C# Programming Guide)
; https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

그래도 이해가 안 되는 부분이 있으면 다시 질문해 주세요.

참고로, 제 책을 가지고 있다면 "8.7 확장 메서드" 절을 보시면 됩니다.
정성태
2023-04-07 09시50분
[guest] 감사합니다
[guest]
2023-04-07 02시07분
[guest] 가장 유용한 용도는 sealed 클래스 처럼 상속이 안되는 경우처럼
main class를 수정하기 번거로운 경우로 이해했습니다

기본형은 namespace까지 별도로 꼭 구성해줘야 하나요?

using System;
using Extension;

namespace Extension
{
    public static class ExtensionMethod
    {
        public static int Multiplication(this int var, int a, int b)
        {
            int result = var;
            for (int i = 0; i < b; i++)
                result *= a;
            return result;
        }
    }
}

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}", 5.Multiplication(2, 3));
        }
    }
}
[guest]
2023-04-07 02시13분
질문이, 위의 덧글 소스코드에서 namespace Extension 블록 없이 public static class ExtensionMethod를 정의하면 빌드가 안 된다는 건가요?
정성태

NoWriterDateCnt.TitleFile(s)