簡體   English   中英

C#方法簽名中的“ this”指的是什么?是否有VB.NET的等效項?

[英]What does “this” refer to in a C# method signature and is there a VB.NET equivalent?

我一直在看的ASP.NET MVC店面 再次系列視頻和看到的東西,我從來沒有注意到或祈禱,任何關注前。 我注意到各種方法的簽名列表中this都有很多引用。 這是一個示例:

public static Category WithCategoryName(this IList<Category> list, string categoryName)   
{
    return 
    (
        from s in list
        where s.Name.Equals(categoryName, StringComparison.InvariantCultureIgnoreCase)
        select s
    )
    .SingleOrDefault();
}

我立刻就明白了IList<Category> liststring categoryName中的簽名,但感到無所適從this呢。

因此,作為95%VB的人,我將代碼彈出到我最喜歡的轉換器中,並得到:

<System.Runtime.CompilerServices.Extension>
Public Shared Function WithCategoryName(list As IList(Of Category), categoryName As String) As Category

    Return 
    (
        From s In list 
        Where s.Name.Equals(categoryName, StringComparison.InvariantCultureIgnoreCase)
        Select s
    )
    .SingleOrDefault()

End Function

首先,我不完全知道為什么<System.Runtime.CompilerServices.Extension>被列入,也許它只是轉換器,不過,你可以看到, this並沒有轉化成任何東西,我可以告訴,除非它有與上述<System.Runtime.CompilerServices.Extension>

所以問題是:

  1. this實際上指的是C#方法簽名和/或在C#方法簽名中做什么?
  2. 是否有等效的VB.NET?



對問題1的回答:

因此,我們已經明確表明, this 實際上表示一種擴展方法,並且從給出的答案來看,似乎沒有等效的內聯VB。

我想補充一點,因為我提到了ASP.NET MVC Storefront視頻,所以上面的C#示例是從他的CategoryFilters類中提取的。 我假設這就是您實現所謂的管道和過濾器管道方法的方式。



對問題2的回答:

我假設VB.NET處理擴展方法的方式如下所示:

Imports System.Runtime.CompilerServices 

Public Module StringExtensions 

    <Extension()> _ 
    Public Function IsNullOrBlank(ByVal s As String) As Boolean 
       Return s Is Nothing OrElse s.Trim.Length.Equals(0) 
    End Function 

End Module

那是一種擴展方法。 this指定它是this <parameter>類型的擴展方法,在您的情況下為IList<Category>

這里有一個VB.NET等效項 ,盡管它是一個屬性,而不是關鍵字。

擴展方法需要知道要應用的類型,請注意,這對於泛型來說是顯而易見的。 擴展方法:

public static string GetNameOf(this List<Category> category) { return ""; }

除了List<Category>之外,將無法使用。

這將創建一個擴展方法。

VB.Net沒有與此相關的語法,因此您需要自己應用屬性。

這個出現在那個地方意味着擴展方法

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

這段代碼之后,程序中的任何字符串對象都可以使用此函數,例如

int count = "Hello world".WordCount();  //count would be equal 2

換句話說,這是一種擴展您無法訪問或不允許更改或派生的類型的功能的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM