Where do I put my extension method?

后端 未结 4 1280
我寻月下人不归
我寻月下人不归 2021-01-01 10:34

A senior member here gave me this code:

public static string Truncate(this string value, int maxChars)
{
    return value.Length <= maxChars ? value : val         


        
4条回答
  •  抹茶落季
    2021-01-01 10:43

    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) + " ..";
        }
    }
    

    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);
            }
        }
    }
    

    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);
    

    is translated by the compiler into

    string t = StringExtensions.Truncate(s, 5);
    

提交回复
热议问题