如何使用 c# 扩展方法扩展类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1188224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I extend a class with c# extension methods?
提问by David Glenn
Can extension methods be applied to the class?
扩展方法可以应用于类吗?
For example, extend DateTime to include a Tomorrow() method that could be invoked like:
例如,扩展 DateTime 以包含可以像这样调用的 Tomorrow() 方法:
DateTime.Tomorrow();
I know I can use
我知道我可以使用
static DateTime Tomorrow(this Datetime value) { //... }
Or
或者
public static MyClass {
public static Tomorrow() { //... }
}
for a similar result, but how can I extend DateTime so that I could invoke DateTime.Tomorrow?
对于类似的结果,但如何扩展 DateTime 以便我可以调用 DateTime.Tomorrow?
采纳答案by Andrew Hare
You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appearto be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
除非现有类型被标记为部分,否则您不能向现有类型添加方法,您只能通过扩展方法添加看起来是现有类型成员的方法。在这种情况下,您不能向类型本身添加静态方法,因为扩展方法使用该类型的实例。
There is nothing stopping you from creating your own static helper method like this:
没有什么能阻止您像这样创建自己的静态辅助方法:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Which you would use like this:
你会像这样使用:
DateTime tomorrow = DateTimeHelper.Tomorrow;
回答by ShuggyCoUk
Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.
扩展方法是一种语法糖,用于使第一个参数是类型 T 的实例的静态方法看起来好像它们是 T 上的实例方法。
As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).
因此,在您制作“静态扩展方法”的地方,好处在很大程度上失去了,因为它们比扩展方法更会使代码的读者感到困惑(因为它们看起来是完全限定的,但实际上并未在该类中定义)没有语法增益(例如,能够在 Linq 中以流畅的风格链接调用)。
Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:
由于无论如何您都必须使用 using 将扩展引入范围,因此我认为创建更简单和更安全:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
And then use this in your code via:
然后通过以下方式在您的代码中使用它:
WriteLine("{0}", DateTimeUtils.Tomorrow)
回答by Adrian Godong
The closest I can get to the answer is by adding an extension method into a System.Type
object. Not pretty, but still interesting.
我能得到的最接近答案是在System.Type
对象中添加一个扩展方法。不漂亮,但仍然很有趣。
public static class Foo
{
public static void Bar()
{
var now = DateTime.Now;
var tomorrow = typeof(DateTime).Tomorrow();
}
public static DateTime Tomorrow(this System.Type type)
{
if (type == typeof(DateTime)) {
return DateTime.Now.AddDays(1);
} else {
throw new InvalidOperationException();
}
}
}
Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.
否则,IMO Andrew 和 ShuggyCoUk 有更好的实现。
回答by Meta-Knight
Unfortunately, you can't do that. I believe it would be useful, though. It is more natural to type:
不幸的是,你不能这样做。不过,我相信它会很有用。输入更自然:
DateTime.Tomorrow
than:
比:
DateTimeUtil.Tomorrow
With a Util class, you have to check for the existence of a static method in two different classes, instead of one.
对于 Util 类,您必须检查两个不同类中是否存在静态方法,而不是一个。
回答by Kumu
Use an extension method.
使用扩展方法。
Ex:
前任:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Usage:
用法:
DateTime.Now.Tomorrow();
or
或者
AnyObjectOfTypeDateTime.Tomorrow();
回答by mimo
I would do the same as Kumu
我会和库姆一样
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
but call it like this new DateTime().Tomorrow();
但是这样称呼它 new DateTime().Tomorrow();
Think it makes more seens than DateTime.Now.Tomorrow();
认为它比 DateTime.Now.Tomorrow();
回答by sudhakar
They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending'' methods. Extension methods are not instance members on the type. The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.
它们提供了通过添加新方法来扩展现有类型的能力,而无需对类型进行修改。使用实例方法语法从应用程序中扩展类型的对象调用方法称为“扩展”方法。扩展方法不是类型的实例成员。要记住的关键点是,定义为静态方法的扩展方法仅在命名空间通过 using 指令显式导入应用程序源代码时才在范围内。即使扩展方法被定义为静态方法,它们仍然使用实例语法来调用。
Check the full example here http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201
在此处查看完整示例 http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201
Example:
例子:
class Extension
{
static void Main(string[] args)
{
string s = "sudhakar";
Console.WriteLine(s.GetWordCount());
Console.ReadLine();
}
}
public static class MyMathExtension
{
public static int GetWordCount(this System.String mystring)
{
return mystring.Length;
}
}
回答by Chris Moschini
I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:
我正在寻找类似的东西 - 提供扩展方法的类的约束列表。似乎很难找到一个简洁的列表,所以这里是:
You can't have any private or protected anything - fields, methods, etc.
It must be a static class, as in
public static class...
.Only methods can be in the class, and they must all be public static.
You can't have conventional static methods - ones that don't include a this argument aren't allowed.
All methods must begin:
public static ReturnType MethodName(this ClassName _this, ...)
您不能拥有任何私有或受保护的任何东西 - 字段、方法等。
它必须是一个静态类,如
public static class...
.只有方法可以在类中,并且它们都必须是公共静态的。
您不能使用传统的静态方法 - 不允许使用不包含 this 参数的方法。
所有方法都必须开始:
public static ReturnType MethodName(this ClassName _this, ...)
So the first argument is always the this reference.
所以第一个参数始终是 this 引用。
There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.
这会产生一个隐含的问题——如果你添加需要任何类型的锁的方法,你就不能真正在类级别提供它。通常,您会提供私有实例级锁,但无法添加任何私有字段,这给您留下了一些非常尴尬的选择,例如在某些外部类上将其作为公共静态提供等。变得很冒险。迹象表明 C# 语言在这些.
The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.
解决方法是将您的 Extension Method 类用作常规类的 Facade,并且您的 Extension 类中的所有静态方法只调用真正的类,可能使用Singleton。
回答by Sheo Dayal Singh
We have improved our answer with detail explanation.Now it's more easy to understand about extension method
我们通过详细的解释改进了我们的答案。现在它更容易理解扩展方法
Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.
扩展方法:是一种机制,通过它我们可以扩展现有类的行为,而无需使用子类或修改或重新编译原始类或结构。
We can extend our custom classes ,.net framework classes etc.
我们可以扩展我们的自定义类、.net 框架类等。
Extension method is actually a special kind of static method that is defined in the static class.
扩展方法实际上是在静态类中定义的一种特殊的静态方法。
As DateTime
class is already taken above and hence we have not taken this class for the explanation.
由于DateTime
上面已经上过课,因此我们没有上过这门课来进行解释。
Below is the example
下面是例子
//This is a existing Calculator class which have only one method(Add)
//这是一个现有的计算器类,只有一个方法(添加)
public class Calculator
{
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
// Below is the extension class which have one extension method.
public static class Extension
{
// It is extension method and it's first parameter is a calculator class.It's behavior is going to extend.
public static double Division(this Calculator cal, double num1,double num2){
return num1 / num2;
}
}
// We have tested the extension method below.
class Program
{
static void Main(string[] args)
{
Calculator cal = new Calculator();
double add=cal.Add(10, 10);
// It is a extension method in Calculator class.
double add=cal.Division(100, 10)
}
}