您的位置:首页 > 编程语言 > C语言/C++

C#中扩展方法,C++语言如何实现类似的扩展?

2011-03-08 18:31 525 查看
今天看了一个C#的程序,是关于扩展方法的代码编写和调用。想了好半天但是还是没能参透其中奥妙。

以我个人目前菜鸟的水平,如果要对一个类添加额外的方法除了在本类中进行加方法以外,另外一个方法就是继承该类,在子类中添加方法。

但在C# 语言里出现了一个新的技术(解决方案)名叫扩展方法。

C#代码如下:

class Program
{
static void Main(string[] args)
{

// 调用扩展方法

Console.WriteLine("123456".MD5Hash());

Console.WriteLine("1".In(new[] { "1", "2", "3" }));
}
}

public static class helper
{

public static string MD5Hash(this string s)
{

return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5");

}

public static bool In(this object o, IEnumerable b)
{

foreach (object obj in b)
{

if (obj == o)

return true;

}

return false;

}

}

运行结果:



C#语言居然可以这样子实现,佩服!

我把这个贴出来就是希望高人看到。解答下原因,如果用C++实现类似C#扩展方法一样的功能,那么这样的C++代码该怎样写?

在CSDN上看到一哥们给的答案,自己看了网址链接举得还可以,就贴上来了。

using namespace System; namespace CPPLib
{
[System::Runtime::CompilerServices::Extension]
public ref class StringExtensions abstract sealed
{
public:
[System::Runtime::CompilerServices::Extension]
static bool MyIsNullOrEmpty(String^ s)
{
return String::IsNullOrEmpty(s);
}
};
}

参考:
How do I declare a method in C++/CLI that will be seen as an extension method in C#?
http://stackoverflow.com/questions/995038/how-do-i-declare-a-method-in-c-cli-that-will-be-seen-as-an-extension-method-in
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: