본문 바로가기
개발/게임) 개발관련

c#) 확장형 메소드 (Extension Methods)

by 테샤르 2023. 10. 19.

확장형 메소드 (Extension Methods)

 

확장명 메서드를 사용하면 새 파생 형식을 만들거나 다시 컴파일하거나 원래 형식을 수정하지 않고도 기존 형식에 메서드를 "추가"할 수 있다. 확장 메서드는 정적 메서드이지만 확장 형식의 인스턴스 메서드인 것처럼 호출되고

 C#, F# 및 Visual Basic에서 작성된 클라이언트 코드의 경우 확장명 메서드를 호출하는 것과 형식에 정의된 메서드를 호출하는 데는 명백한 차이가 없는 형식이다.

 

간략한 예시를 보면 다음과 같다.

 

<예시>

using UnityEngine;
using System.Collections;


public static class ExtensionMethods
{

    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

 

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        
        transform.ResetTransformation();
    }
}

 

반응형

 

좀더 간단하게 표현이 가능하고 기존 클래스나 모듈에도 기능을 추가가 가능하다.

기존 코드에 간략하게 이식도 가능하고 협업에도 좋다(재사용, 확장성)

 

 

Micorosoft 확장명 메서드(C# 프로그래밍 가이드) : [링크]

 

확장 메서드 - C# 프로그래밍 가이드 - C#

C#에서 확장명 메서드를 사용하면 새 파생 형식을 만들거나 다시 컴파일하거나 원래 형식을 수정하지 않고도 기존 형식에 메서드를 추가할 수 있습니다.

learn.microsoft.com

 

C# 3.0 Extension Methods : [링크]

 

Extension Methods - The complete C# tutorial

C# 3.0: Extension MethodsAnother cool feature of C# 3.0 is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain st

csharp.net-tutorials.com

 

 

★☆☆☆☆

 

반응형

댓글