惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
TaoSecurity Blog
TaoSecurity Blog
H
Heimdal Security Blog
Help Net Security
Help Net Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
N
News | PayPal Newsroom
V2EX - 技术
V2EX - 技术
博客园 - 【当耐特】
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
C
CERT Recently Published Vulnerability Notes
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy & Cybersecurity Law Blog
有赞技术团队
有赞技术团队
S
Schneier on Security
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
H
Hacker News: Front Page
The Last Watchdog
The Last Watchdog
Schneier on Security
Schneier on Security
PCI Perspectives
PCI Perspectives
IT之家
IT之家
Project Zero
Project Zero
博客园 - 司徒正美
P
Privacy International News Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Jina AI
Jina AI
Security Latest
Security Latest
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
NISL@THU
NISL@THU
Webroot Blog
Webroot Blog
N
Netflix TechBlog - Medium
L
Lohrmann on Cybersecurity

博客园 - 天涯

Prism.Interactivity 和 Prism.Modularity 介绍 Prism BindableBase 和 Commands 的介绍 对 mvvm 架构的理解 wpf mvvm 架构 C#硬件开发业务流程调试技巧 wpf winform 截图 wpf Cannot locate resource 'app.xaml' app.config ConfigSection 保护 程序开发注意4项,你知道吗? .net 变量缓存,你知道吗 wpf 多线程 更新UI 界面 wpf treeview 绑定不同的对象 .net 技术,你掌握了多少 aspx 中确认删除 脚本 - 天涯 奇怪--ORA-12154:TNS:无法处理服务名: 建模十条原则 由软件加壳谈起 Hashtable 应注意的 2 点 vb 调用c#做的com 组件
.net 中对类的扩展
天涯 · 2009-08-18 · via 博客园 - 天涯

扩展方法可以使你来扩展一个已存在的类型,增加它的方法,而无需继承它或者重新编译。所以不像为对象写助手方法,扩展方法可以直接是对象自己的一部分。

一个示例,假设我们想要验证一个string是不是合法的Email地址,我们可以编写一个方法,输入为一个string并且返回true或者false。现在,使用扩展方法,我们可以如下这样做:

public static class MyExtensions {

    public static bool IsValidEmailAddress(this string s) {

        Regex regex = new Regex( @"^[w-.]+@([w-]+.)+[w-]{2,4}$" );

        return regex.IsMatch(s);

    }

}

我们定义了一个带有静态方法的静态类。注意,那个静态方法在参数类型string前面有一个this关键词,这会告诉编译器这个特殊的扩展方法会增加给string类型的对象。于是我们就可以在string中调用这个成员方法:

using MyExtensions;

string email = Request.QueryString["email"];

if ( email.IsValidEmailAddress() ) {

    // ...

}

  当然除了该中方法之外,只要你在类前加了partial ,你也可以直接在另一个文件里命名同样的类,来添加你需要的方法。

例如:

  namespace PC
{
    partial class A { }
}

namespace PC
{
    partial class A { }
}

 这两个类实际上是一个类。这样就可以将自动生成的代码,和自己编写的代码分开。容易进行代码控制。