C# 扩展方法未定义

标签 c# .net-4.0 extension-methods

我有一个非常基本的扩展方法:

namespace PHPImport
{
    public static class StringExtensionMethods
    {
        public static bool IsNullEmptyOrWhiteSpace(this string theString)
        {
            string trimmed = theString.Trim();

            if (trimmed == "\0")
                return true;

            if (theString != null)
            {
                foreach (char c in theString)
                {
                    if (Char.IsWhiteSpace(c) == false)
                        return false;
                }
            }

            return true;
        }
    }
}

我试图在同一个项目(单独的 .cs 文件)、同一个命名空间中使用它,我得到一个 'string' does not contain a definition for 'IsNullEmptyOrWhiteSpace' 错误。

namespace PHPImport
{
    class AClassName: AnInterface
    {
        private void SomeMethod()
        {
             if (string.IsNullEmptyOrWhiteSpace(aStringObject)) { ... }
        }
    }
}

我已经尝试重建/清理解决方案,并重新启动 visual studio 无济于事。

有什么想法吗?

最佳答案

因为你把它作为一个扩展方法,你需要这样调用它:

if (aStringObject.IsNullEmptyOrWhiteSpace())

它将用法“扩展”到字符串 实例,它不会向 String 类添加新的静态方法,这将由您当前的调用语法建议。

关于C# 扩展方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412117/

相关文章:

c# - 如何最好地检查 cookie 是否存在?

c# - LDAP 请求和响应是什么样的?

visual-studio-2010 - VSTS 2010 SGEN : error : Could not load file or assembly (Exception from HRESULT: 0x80131515)

c# - 部分类与扩展方法

c# - 有没有办法将 xml 转换为 json?

c# - NuGet 恢复从不在构建服务器上运行

c# - 从 EventLog.CreateEventSource 接收 "...has already been registered..."即使我正在检查 !EventLog.SourceExists

c# - 匿名类型的编译器优化

c# - 从 IDataReader 获取值的 Null 安全方法

c# - 如何关闭 resharper 中的 "Convert Extension Method to Plain Static"自动重构?