code

C # 확장 메서드로 클래스를 확장하려면 어떻게해야합니까?

codestyles 2020. 8. 31. 07:49
반응형

C # 확장 메서드로 클래스를 확장하려면 어떻게해야합니까?


확장 메서드를 클래스에 적용 할 수 있습니까?

예를 들어 다음과 같이 호출 할 수있는 Tomorrow () 메서드를 포함하도록 DateTime을 확장합니다.

DateTime.Tomorrow();

내가 사용할 수 있다는 걸 알아

static DateTime Tomorrow(this Datetime value) { //... }

또는

public static MyClass {
  public static Tomorrow() { //... }
}

비슷한 결과를 얻을 수 있지만 DateTime.Tomorrow를 호출 할 수 있도록 DateTime을 어떻게 확장 할 수 있습니까?


기존 유형이 부분으로 표시되지 않는 한 기존 유형에 메소드를 추가 할 수 없습니다 . 확장 메소드를 통해 기존 유형의 멤버로 보이는 메소드 만 추가 할 수 있습니다 . 이 경우 확장 메서드는 해당 형식의 인스턴스를 사용하므로 형식 자체에 정적 메서드를 추가 할 수 없습니다.

다음과 같은 정적 도우미 메서드를 만드는 데 방해가되는 것은 없습니다.

static class DateTimeHelper
{
    public static DateTime Tomorrow
    {
        get { return DateTime.Now.AddDays(1); }
    }
}

다음과 같이 사용합니다.

DateTime tomorrow = DateTimeHelper.Tomorrow;

확장 방법을 사용하십시오 .

전의:

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }    
    }
}

용법:

DateTime.Now.Tomorrow();

또는

AnyObjectOfTypeDateTime.Tomorrow();

확장 메서드는 첫 번째 매개 변수가 T 유형의 인스턴스 인 정적 메서드를 T의 인스턴스 메서드 인 것처럼 보이게 만들기위한 구문 설탕입니다.

따라서 '정적 확장 메서드'를 만드는 경우에는 확장 메서드보다 코드 독자를 혼란스럽게하는 역할을하기 때문에 이점이 크게 손실됩니다 (완전한 것으로 보이지만 실제로 해당 클래스에 정의되어 있지 않기 때문에). 구문 상 이득이 없습니다 (예를 들어 Linq 내에서 유창한 스타일로 통화를 연결할 수 있음).

어쨌든 using을 사용하여 확장을 범위로 가져와야하므로 생성하는 것이 더 간단하고 안전하다고 주장합니다.

public static class DateTimeUtils
{
    public static DateTime Tomorrow { get { ... } }
}

그리고 다음을 통해 코드에서 이것을 사용하십시오.

WriteLine("{0}", DateTimeUtils.Tomorrow)

내가 답을 얻을 수있는 가장 가까운 방법은 System.Type객체에 확장 메서드를 추가하는 것입니다. 예쁘지는 않지만 여전히 흥미 롭습니다.

public static class Foo
{
    public static void Bar()
    {
        var now = DateTime.Now;
        var tomorrow = typeof(DateTime).Tomorrow();
    }

    public static DateTime Tomorrow(this System.Type type)
    {
        if (type == typeof(DateTime)) {
            return DateTime.Now.AddDays(1);
        } else {
            throw new InvalidOperationException();
        }
    }
}

Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.


I would do the same as Kumu

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
           return date.AddDays(1);
        }    
    }
}

but call it like this new DateTime().Tomorrow();

Think it makes more seens than DateTime.Now.Tomorrow();


They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending’’ methods. Extension methods are not instance members on the type. The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.

Check the full example here http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201

Example:

class Extension
    {
        static void Main(string[] args)
        {
            string s = "sudhakar";
            Console.WriteLine(s.GetWordCount());
            Console.ReadLine();
        }

    }
    public static class MyMathExtension
    {

        public static int GetWordCount(this System.String mystring)
        {
            return mystring.Length;
        }
    }

I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:

  1. You can't have any private or protected anything - fields, methods, etc.

  2. It must be a static class, as in public static class....

  3. Only methods can be in the class, and they must all be public static.

  4. You can't have conventional static methods - ones that don't include a this argument aren't allowed.

  5. All methods must begin:

    public static ReturnType MethodName(this ClassName _this, ...)

So the first argument is always the this reference.

There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.

The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.


Unfortunately, you can't do that. I believe it would be useful, though. It is more natural to type:

DateTime.Tomorrow

than:

DateTimeUtil.Tomorrow

With a Util class, you have to check for the existence of a static method in two different classes, instead of one.


We have improved our answer with detail explanation.Now it's more easy to understand about extension method

Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.

We can extend our custom classes ,.net framework classes etc.

Extension method is actually a special kind of static method that is defined in the static class.

As DateTime class is already taken above and hence we have not taken this class for the explanation.

Below is the example

//This is a existing Calculator class which have only one method(Add)

public class Calculator 
{
    public double Add(double num1, double num2)
    {
        return num1 + num2;
    }

}

// Below is the extension class which have one extension method.  
public static class Extension
{
    // It is extension method and it's first parameter is a calculator class.It's behavior is going to extend. 
    public static double Division(this Calculator cal, double num1,double num2){
       return num1 / num2;
    }   
}

// We have tested the extension method below.        
class Program
{
    static void Main(string[] args)
    {
        Calculator cal = new Calculator();
        double add=cal.Add(10, 10);
        // It is a extension method in Calculator class.
        double add=cal.Division(100, 10)

    }
}

참고URL : https://stackoverflow.com/questions/1188224/how-do-i-extend-a-class-with-c-sharp-extension-methods

반응형