本文介绍了装饰图案&扩展方法在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先要描述我的问题,我想定义Decorator和扩展方法
装饰器

扩展方法

我在c#中有以下代码片段

  public interface IMyInterface 
{
void Print();
}

public static class Extension
{
public static void PrintInt(this IMyInterface myInterface,int i)
{
Console.WriteLine
(Extension.PrintInt(this IMyInterface myInterface,int i));
}

public static void PrintString(this IMyInterface myInterface,string s)
{
Console.WriteLine
(Extension.PrintString(this IMyInterface myInterface ,string s));
}
}

public class Imp:IMyInterface
{
#region IMyInterface成员

public void Print()
{
Console.WriteLine(Imp);
}

#endregion
}

类程序
{
static void Main(string [] args)
{
Imp obj = new Imp();
obj.Print();
obj.PrintInt(10);
}
}

在上面的代码中,我将扩展接口而不修改现有的代码,这两个方法可用于派生类。所以我的问题是:扩展方法是否替代了装饰器模式?

解决方案

扩展方法真的只是语法糖用于调用静态方法。



尽管使用装饰器,您实际上可以更改装饰类的行为,扩展方法只能在类上更改属性或调用方法,就像普通静态方法。



装饰模式实际上被定义为使用包装器来改变行为,扩展方法显然不会做。


Before going to describe my problem first,I would like to define definitions of Decorator and Extension methodDecorator

Extension method

I have following code snippet in c#

public interface IMyInterface
{
    void Print();
}

public static class Extension
{
    public static void PrintInt(this IMyInterface myInterface, int i)
    {
        Console.WriteLine
            ("Extension.PrintInt(this IMyInterface myInterface, int i)");
    }

    public static void PrintString(this IMyInterface myInterface, string s)
    {
        Console.WriteLine
            ("Extension.PrintString(this IMyInterface myInterface, string s)");
    }
}

public class Imp : IMyInterface
{
    #region IMyInterface Members

    public void Print()
    {
        Console.WriteLine("Imp");
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        Imp obj = new Imp();
        obj.Print();
        obj.PrintInt(10);
    }
}

In the above code I am extending interface without modifying the existing code,and these two methods are available to derived class. So my question is this: Is the extension method a replacement of the decorator pattern?

解决方案

A extension method is really just syntactic sugar for calling a static method.

While with a decorator you could actually change the behaviour of your decorated class, a extension method could only alter properties or call methods on your class, just like an "ordinary" static method.

Decorator pattern is actually definied as using a wrapper to alter behaviour, which a extension method clearly doesn't do.

这篇关于装饰图案&扩展方法在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:22