Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使这个字符串扩展方法工作?_C#_.net_Extension Methods - Fatal编程技术网

C# 如何使这个字符串扩展方法工作?

C# 如何使这个字符串扩展方法工作?,c#,.net,extension-methods,C#,.net,Extension Methods,我有这个扩展方法,但我不知道如何正确使用它。代码如下 public static bool string.isPalindrome() { } 我知道回文是什么,也知道如何将其编码出来,但如何使用此方法来检查字符串是否为回文?您提到的扩展方法在原始帖子中没有正确定义。其定义如下: public static bool IsPalindrome(this string input) { // Here you will place the code that will check

我有这个扩展方法,但我不知道如何正确使用它。代码如下

public static bool string.isPalindrome()
{

}

我知道回文是什么,也知道如何将其编码出来,但如何使用此方法来检查字符串是否为回文?

您提到的扩展方法在原始帖子中没有正确定义。其定义如下:

public static bool IsPalindrome(this string input)
{ 
    // Here you will place the code that will check 
    // if string called input is Palindrome.
}
public static class Extensions
{
    public static bool IsPalindrome(this string input)
    { 
        // Here you will place the code that will check 
        // if string called input is Palindrome.
    }
}
顺便说一下,您的方法应该包含在静态类中,如下所示:

public static bool IsPalindrome(this string input)
{ 
    // Here you will place the code that will check 
    // if string called input is Palindrome.
}
public static class Extensions
{
    public static bool IsPalindrome(this string input)
    { 
        // Here you will place the code that will check 
        // if string called input is Palindrome.
    }
}
最后但并非最不重要的一点是,您可以按如下方式使用它:

inputString.IsPalindrome();

其中inputString是要检查的字符串

如果要使用扩展方法,请使用this关键字,如中所述:


可以使用以下代码在String类上定义isPalindrome扩展:


这不是一个有效的扩展方法声明,首先。。。你为什么不先把它编码成一个扩展方法,然后阅读扩展方法,然后再把它转换成一个呢?这就是我的导师给我的方法名称,我们并没有真正涵盖很多扩展方法。谢谢你的帮助。这是一个非常合理的方法名,但是方法声明是无效的。网络上有很多关于扩展方法的资源-在提出问题之前,你是否查找了其中的任何一种?请投票人解释一下我错在哪里?谢谢。我没有,但我想是因为你最初的答案是错的。@Patrickhoffman非常感谢你,但几分钟后我得到了两张Donwvots票,这是我最后一次更新。无论如何,我比你更喜欢。我会放弃你答案的第一部分,因为它对我来说既不正确也没有帮助。@Christos,现在你答案的最后一部分是不正确的。你不能像那样使用扩展方法=