"这"扩展方法中的关键字 [英] "this" keyword in Extension methods

查看:88
本文介绍了"这"扩展方法中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于this关键字在Extension方法中的含义。以下是 http:// weblogs的示例。 asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx [ ^ ]:



  public   static   class  ScottGuExtensions 
{
public static < span class =code-keyword> bool IsValidEmailAddress( this string s)
{
正则表达式regex = 正则表达式( @ ^ [。\w-\] + @([\w - ] + \。)+ [\\瓦特 - ] {2,4} $);
return regex.IsMatch(s);
}
}





在网站上显示this表示此扩展方法应适用于具有字符串类型的对象。我不明白的是,如果我们没有在参数声明中加入this,它仍然意味着同样的事情。所以差别就输给了我。欢迎任何帮助。

解决方案

);
return 正则表达式。 IsMatch(s);
}
}





在网站上显示this表示此扩展名方法应该应用于具有字符串类型的对象。我不明白的是如果我们没有在参数声明中放入this,它仍然意味着同样的事情。所以差别对我来说是丢失的。任何帮助欢迎。


这是一个语法问题。this关键字只标记你为该参数的类型做了一个扩展方法。但我喜欢这种语法,因为它是非常符合关键字的其他用法。


使用'扩展'方法:

  public   static   class  ScottGuExtensions 
{
公共 static bool IsValidEmailAddress( this string s)
{
Regex regex = new Regex( @ ^ [\w-\。] + @([\\\ - ] + \。)+ [\\ \\w - ] {2,4}

Hi, my question is about "this" keyword's meaning in Extension methods. Here's an example from http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx[^]:

public static class ScottGuExtensions
{
    public static bool IsValidEmailAddress(this string s)
    {
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        return regex.IsMatch(s);
    }
}



In the website it says "this" means that this Extension Method should be applied to object with a string type. What i don't get it is if we didn't put "this" in parameter declaration, it would still mean the same thing. So the difference is lost to me. Any help is welcome.

解决方案

"); return regex.IsMatch(s); } }



In the website it says "this" means that this Extension Method should be applied to object with a string type. What i don't get it is if we didn't put "this" in parameter declaration, it would still mean the same thing. So the difference is lost to me. Any help is welcome.


It is a matter of syntax. The "this" keyword is only marking that you make an extension method for the type of that parameter. But I like this syntax because it is really in line with the keyword's other usage.


With the 'extension' method:

public static class ScottGuExtensions
{
    public static bool IsValidEmailAddress(this string s)
    {
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}


这篇关于&QUOT;这&QUOT;扩展方法中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆