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

推荐订阅源

S
Security Affairs
美团技术团队
量子位
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
Apple Machine Learning Research
Apple Machine Learning Research
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
N
Netflix TechBlog - Medium
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cyber Attacks, Cyber Crime and Cyber Security
Recent Announcements
Recent Announcements
Cisco Talos Blog
Cisco Talos Blog
L
LangChain Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 三生石上(FineUI控件)
U
Unit 42
T
Tenable Blog
Security Latest
Security Latest
Scott Helme
Scott Helme
B
Blog
C
Cybersecurity and Infrastructure Security Agency CISA
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
A
Arctic Wolf
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
酷 壳 – CoolShell
酷 壳 – CoolShell
I
Intezer
Know Your Adversary
Know Your Adversary
云风的 BLOG
云风的 BLOG
有赞技术团队
有赞技术团队
雷峰网
雷峰网
The Cloudflare Blog
Cloudbric
Cloudbric
Latest news
Latest news
Project Zero
Project Zero
S
Secure Thoughts
V
Visual Studio Blog
博客园 - Franky
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
W
WeLiveSecurity

博客园 - 天涯

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 { }
}

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