扩展方法通用Vb到c#

时间:2016-06-06 09:46:30

标签: c# vb.net extension-methods

我在将方法扩展从VB.NET转换为C#时遇到问题,这是我正在使用的VB.NET代码

Module ClientBaseExtensions
    Private Const HDR_TOKEN = "Token"

    <Extension()>
    Public Sub Initialize(Of T As Class)(ByVal client As ClientBase(Of T), url As String, pToken As String, pDeviceId As String)
        client.Endpoint.Address = New EndpointAddress(url)
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty
    End Sub
End Module

当自动转换它时,它会给我这个在我的基于客户端的对象中无法识别的代码

static class ClientBaseExtensions
{

    private const  HDR_TOKEN = "Token";

    public static void Initialize<T>(ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
    {
        client.Endpoint.Address = new EndpointAddress(url);
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

在C#中,通过为第一个参数(定义扩展类型的参数)指定this关键字来声明扩展方法:

static class ClientBaseExtensions
{

    private const  HDR_TOKEN = "Token";

                           // insert this here
    public static void Initialize<T>(this ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
    {
        client.Endpoint.Address = new EndpointAddress(url);
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

    }
}