2012-05-02 24 views
0

拡張メソッドを同等の.NET 2.0に置き換えることで、このコードを.NET 2.0互換に変更するにはどうすればよいですか?.NET 2.0相当のC#拡張メソッド

public interface IMessagingService { 
    void sendMessage(object msg); 
} 
public interface IServiceLocator { 
    object GetService(Type serviceType); 
} 
public static class ServiceLocatorExtenstions { 
    //.NET 3.5 or later extension method, .NET 2 or earlier doesn't like it 
    public static T GetService<T>(this IServiceLocator loc) { 
     return (T)loc.GetService(typeof(T)); 
    } 
} 
public class MessagingServiceX : IMessagingService { 
    public void sendMessage(object msg) { 
     // do something 
    } 
} 
public class ServiceLocatorY : IServiceLocator { 
    public object GetService(Type serviceType) { 
     return null; // do something 
    } 
} 
public class NotificationSystem { 
    private IMessagingService svc; 
    public NotificationSystem(IServiceLocator loc) { 
     svc = loc.GetService<IMessagingService>(); 
    } 
} 
public class MainClass { 
    public void DoWork() { 
     var sly = new ServiceLocatorY(); 
     var ntf = new NotificationSystem(sly); 
    } 
} 

ありがとうございました。

+0

なぜ拡張メソッドを使用する必要がありますか?拡張クラスをIServiceLocatorで行う関数プロバイダーとして機能させます。 – SimpleVar

答えて

5

拡張メソッドからthisキーワードを削除するだけです。

public static class ServiceLocatorExtensions 
{  
    public static T GetService<T>(IServiceLocator loc) { 
     return (T)loc.GetService(typeof(T)); 
    } 
} 

そして、あなたは「拡張」されているオブジェクトのインスタンスを渡すことにより、他の静的メソッドとしてそれを呼び出す:実は、これは.NET 3.5のコンパイラは、シーンの背後に何をするかである

IServiceLocator loc = GetServiceLocator(); 
Foo foo = ServiceLocatorExtensions.GetService<Foo>(loc); 

を。 Btw接尾辞Extensionsも削除できます。例えば。人々を混乱させないためにHelperを使用してください。

3
svc = loc.GetService<IMessagingService>(); 

しかし、あなたが拡張メソッドを削除し、まだ.NET 2.0をターゲットにする必要はありません

svc = ServiceLocatorExtenstions.GetService<IMessagingService>(loc); 

に等しい - (グーグルの詳細を)この記事をチェックしてください。http://kohari.org/2008/04/04/extension-methods-in-net-20/

1

あなたドン場合拡張メソッドを使用してコード内のあいまいさを避けたいのであれば、インターフェイス定義内のすべてのServiceLocatorExtenstionsメソッドを移動し、ServiceLocatorExtenstionsクラスを削除するのが一番の解決策です。

しかし、この1つは、おそらくより多くの作業を含み、ここでは他の解決策が含まれ、より一貫した結果が得られます。

1

ジェネリックメソッドをあなたのインターフェースに入れてみませんか?あなたの拡張メソッドは呼び出しを簡単にするだけなので、最初のほうを簡単にするほうがいいですか?

.NET 2.0で拡張メソッドを使用する方法があります。hereまたはhereを参照してください。

関連する問題