![](/img/trans.png)
[英]What is the VB.NET equivalent of passing 'this' in a method signature in C#.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> list
和string 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>
。
所以问题是:
this
实际上指的是C#方法签名和/或在C#方法签名中做什么? 因此,我们已经明确表明, this
实际上表示一种扩展方法,并且从给出的答案来看,似乎没有等效的内联VB。
我想补充一点,因为我提到了ASP.NET MVC Storefront视频,所以上面的C#示例是从他的CategoryFilters
类中提取的。 我假设这就是您实现所谓的管道和过滤器或管道方法的方式。
我假设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.