我一直收到此错误消息,我不知道为什么

时间:2015-10-23 17:59:21

标签: c#

错误信息是:

  

'_ djv.Authenticator'不包含'authenticate'的定义   没有扩展方法'authenticate'接受第一个参数   类型'_djv.Authenticator'可以找到(你错过了使用   指令或程序集引用?)我的代码在下面,我有一个   控制台应用程序和一个名为authenticator的类,两者都有   代码在那里。

namespace _Authenticator 
{
    public class Authenticator 
    {
        private Dictionary < string, string > dictionary = new Dictionary < string, string > ();

        public Authenticator() 
        {
            dictionary.Add("username1", "password1");
            dictionary.Add("username2", "password2");
            dictionary.Add("username3", "password3");
            dictionary.Add("username4", "password4");
            dictionary.Add("username5", "password5");
        }

        public bool authenticate(string username, string password) 
        {
            bool authenticated = false;

            if (dictionary.ContainsKey(username) && dictionary[username] == password) 
            {
                authenticated = true;
            }
            else 
            {
                authenticated = false;
            }

            return authenticated;
        }
    }
}

using _Authenticator;

namespace _djv 
{
    class Authenticator 
    {
        static void Main(string[] args) 
        {
            Console.WriteLine("Please enter a username");
            var username = Console.ReadLine();

            Console.WriteLine("Please enter your password");
            var password = Console.ReadLine();

            var auth = new Authenticator();

            if (auth.authenticate(username, password)) 
                Console.WriteLine("Valid username/password combination");
            else 
                Console.WriteLine("Invalid username/password combination");

            Console.WriteLine("Press Enter to end");
            Console.ReadLine();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

有一个类名冲突。您的auth变量引用_djv命名空间中的类。指定可以使用它的类的全名。

var auth = new _Authenticator.Authenticator();

或者,您可以为该类创建别名。我在这里推荐这种方法,因为它使编写代码变得不那么乏味。

using Auth = _Authenticator.Authenticator;
(...)
var auth = new Auth();

实际上,我认为最好的想法是重命名其中一个类。一切都会变得更加清洁和清晰。

答案 1 :(得分:1)

您有两个名为Authenticator的课程。如果未明确指定名称空间,则将使用当前名称空间中的类(在这种情况下,这是错误的)。

您可以通过以下方式解决:

  1. 明确创建正确类的实例

    var auth = new _Authenticator.Authenticator()

  2. 将您的主要课程重命名为其他内容,例如Main

  3. 我强烈建议选项2,以防止进一步混淆。

相关问题