我一直得到这个错误信息,我不知道为什么

本文关键字:信息 我不知道 为什么 错误 一直 | 更新日期: 2023-09-27 18:19:03

错误信息为:

_djv。"验证器"不包含"身份验证"的定义。并且没有接受第一个参数的扩展方法authenticate"_djv类型。可以找到Authenticator'(您是否缺少一个using指令或汇编参考?)我的代码如下,我有一个控制台应用程序和一个叫做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();
        }
    }
}

我一直得到这个错误信息,我不知道为什么

类名冲突。您的auth变量指的是_djv名称空间中的类。指定能够使用它的类的全名。

var auth = new _Authenticator.Authenticator();

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

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

实际上,我认为最好的办法是重命名其中一个类。

你有两个类叫做Authenticator。如果没有显式地指定命名空间,将使用当前命名空间中的类(在这种情况下是错误的)。

你可以用以下两种方法求解:

  1. 显式创建一个正确类的实例

    var auth = new _Authenticator.Authenticator()

  2. 将你的主类重命名为其他东西,例如Main

我强烈推荐选项2,以避免进一步的混淆。