如何创建原型方法(如JavaScript)的C#.NET? [英] How can I create Prototype Methods (like JavaScript) in C#.Net?

查看:123
本文介绍了如何创建原型方法(如JavaScript)的C#.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这怎么可能做出原型方法,C#.NET?

How is it possible to make prototype methods in C#.Net?

在JavaScript中,我可以执行以下操作来为string对象创建修剪方法:

In JavaScript, I can do the following to create a trim method for the string object:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

我如何去用C#.net这样做呢?

How can I go about doing this in C#.Net?

推荐答案

您不能动态地添加方法将现有对象或类.NET,除非改变源为类。

You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.

然而,你可以,在C#3.0中,使用扩展方法,其中的的像新的方法,但编译时的法宝。

You can, however, in C# 3.0, use extension methods, which look like new methods, but are compile-time magic.

要为你的code做到这一点:

To do this for your code:

public static class StringExtensions
{
public static String trim(this String s)
{
return s.Trim();
}
}

要使用它:

String s = "  Test  ";
s = s.trim();

这看起来像是一种新的方法,但将编译完全相同的方式,因为这code:

This looks like a new method, but will compile the exact same way as this code:

String s = "  Test  ";
s = StringExtensions.trim(s);

究竟是什么你要完成?也许还有做你想要什么更好的办法?

What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?

这篇关于如何创建原型方法(如JavaScript)的C#.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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