我的扩展方法放在哪里? [英] Where do I put my extension method?
问题描述
这里的一位资深成员给了我这段代码:
A senior member here gave me this code:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + " ..";
}
他说将其用作扩展方法。但是我在哪里放置这种方法呢?似乎它向.Net
He said to use it as an extension method. But where do I put this method? It looks like it adds something to .Net
推荐答案
添加了一些内容,请考虑一个名为 StringExtensions $ c $的类。 c>像这样:
Consider a class named StringExtensions
like so:
static class StringExtensions
{
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ?
value :
value.Substring(0, maxChars) + " ..";
}
}
请确保您将此类放在任何命名空间中,您需要为该命名空间添加 using
声明。
Be sure that whatever namespace you put this class in, you include a using
declaration for that namespace.
因此,举一个完整的例子:
Thus, for a full example:
StringExtensions.cs
:
namespace My.Extensions
{
static class StringExtensions
{
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ?
value :
value.Substring(0, maxChars) + " ..";
}
}
}
Program.cs
:
using System;
using My.Extensions;
namespace My.Program
{
static class Program
{
static void Main(string[] args)
{
string s = "Hello, World";
string t = s.Truncate(5);
Console.WriteLine(s);
Console.WriteLine(t);
}
}
}
顺便说一句,不将其添加到.NET。您甚至都没有向 String
类添加新方法。而是,这是一个编译器技巧,它使静态方法位于第一个声明为 this * TypeName * * valueParameter *
的静态类中,其中 * TypeName *
是类型的名称,而 * valueParameter *
是参数的名称,可以使该名称作为实例方法出现在类型名称为 * TypeName *
的类型。那就是
By the way, you are not adding it to .NET. You are not even adding a new method to the class String
. Rather, it's a compiler trick that makes static methods living in static classes with their first parameter declared as this *TypeName* *valueParameter*
where *TypeName*
is the name of a type, and *valueParameter*
is the name of the parameter can be made to appear as an instance method on instances of the type with type name *TypeName*
. That is
string t = s.Truncate(5);
由编译器翻译为
string t = StringExtensions.Truncate(s, 5);
这篇关于我的扩展方法放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!