简体   繁体   English

为什么我的C#扩展方法在此控制台应用程序中不起作用?

[英]Why doesnt my C# extension method work in this console app?

I have the console app: 我有控制台应用程序:

namespace LicenceCreator
{
    class Program
    {  
        static void Main(string[] args)
        {
        }    

        public static string TrimTextAndAppendDots(
            this string stringArg, int maxLengthArg)
        {
            string retString;

            if (stringArg.Length > maxLengthArg)
            {
                retString = stringArg.Substring(0, maxLengthArg) + "...";
            }
            else
            {
                retString = stringArg;
            }

            return retString;
        }
    }
}

But for some reason the extension method isnt picked up when I call it from a string in the main method any ideas why? 但是由于某种原因,当我从main方法中的字符串调用扩展方法时,并没有选择该扩展方法,这是为什么?

I'm guessing that by "isn't picked up", you mean "the compiler complains that it can't find it". 我猜这是“未拾取”,您的意思是“编译器抱怨找不到它”。 Then: 然后:

The extension method must be in a "static" class and you must have a "using" directive pointing to the namespace of that class. 该扩展方法必须在“静态”类中,并且您必须具有指向该类名称空间的“ using”指令。 Do you? 你呢?

If it's "the compiler doesn't complain but the string doesn't change" then maybe you are calling it as 如果它是“编译器没有抱怨但字符串没有改变”,则可能是您将其称为

 myString.TrimTextAndAppendDots(10);

instead of 代替

 myString = myString.TrimTextAndAppendDots(10);

Extension methods must be declared within a static class. 扩展方法必须在静态类中声明。

  • Is extension method's class static? 扩展方法的类是静态的吗?

In order to call an extension method, declaring class' namespace must be referenced: 为了调用扩展方法,必须引用声明类的名称空间:

  • Have you added class assembly reference? 是否添加了类汇编参考?
  • Have you declared the corresponding "using" statement for extension methods class' namespace? 您是否为扩展方法类的名称空间声明了相应的“ using”语句?

UPDATE: 更新:

Answering to your comment, I find my answer correct anyway, but now we can add: 回答您的评论,我仍然找到正确的答案,但是现在我们可以添加:

  • Is your "Program" class static? 您的“程序”类是静态的吗? ;) ;)

Extensions have to be on a static class, just like this: 扩展必须在静态类上,如下所示:

public static class StringExtension
{
    public static string TrimTextAndAppendDots(this string stringArg, int maxLengthArg)
    {
        string retString = "";

        if (stringArg.Length > maxLengthArg)
        {
            retString = stringArg.Substring(0, maxLengthArg) + "...";
        }
        else
        {
            retString = stringArg;
        }

        return retString;
    }
}

And finally you have to declare StringExtension with using statement wherever you want to use said extension methods 最后,无论您要在何处使用上述扩展方法,都必须使用using语句声明StringExtension

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM