如何编写通用方法以及如何在c#中编写扩展方法? [英] how to write common method and how to write extented method in c# ?

查看:109
本文介绍了如何编写通用方法以及如何在c#中编写扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中编写通用方法和扩展方法?
请发布示例常用方法吗?

How to write common method and how to write extented method in c#?
please post with sample common method?

推荐答案

有一个扩展方法示例
There is a sample for extension methods here[^].

Im not quite sure what you mean by common methods.


我不知道您用通用"方法表示什么.

扩展方法是一种扩展类而无需派生一个全新的类来实现新功能的方法.

您需要创建public static class(可以为它指定任何名称,因为它是静态的,并且不必实例化它),然后将方法放入其中:

I have no idea what you mean by a "common" method.

An extension method is a method that extends a class without having to derive a whole new class to implement new functionality.

You need to create public static class (it can be given any name you want because it''s static, and you don''t have to instantiate it), and put your method in it:

public static class ExtensionMethods
{
    public static string Append(this string text, string newText)
    {
        string result = text + newText;
        return result;
    }
}



您可以这样称呼:



You call it like this:

string x = "123";
x = x.Append("456");



调用Append后,变量 x 将包含"123456".

请注意,方法必须为static,然后注意参数.第一个表示要扩展的对象,第二个表示要附加的文本.

您确实应该学习如何使用Google,因为这将是您学习扩展方法的详细信息.



After the call to Append, the variable x will contain "123456".

Notice that the method MUST be static, and then notice the parameters. the first one indicates the object being extended, and the 2nd one is the text to be appended.

You really should learn how to use google, because hat''s how you''re going to learn the details about extension methods.


我相信操作人员对此处的术语感到困惑.我怀疑用普通方法他是指静态方法.通过扩展方法,他表示覆盖基本方法的方法.显然他具有Java背景.

有关静态类/方法的信息,请参见:

http://msdn.microsoft.com/en-us/library/79b3xss3 (v = VS.100).aspx [ http://msdn.microsoft.com/en-us/library/ms173149.aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/6fawty39.aspx [ ^ ]
I believe the OP''s confused about terminology here. I suspect by common methods he means static methods. And by extended methods he means methods that override base methods. Apparently he has a Java background.

For info on static classes/methods, see:

http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx[^]

For info on inheriting and overriding methods, see:

http://msdn.microsoft.com/en-us/library/ms173149.aspx[^]

http://msdn.microsoft.com/en-us/library/6fawty39.aspx[^]


这篇关于如何编写通用方法以及如何在c#中编写扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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