[英]I keep getting an error called “TypeIntializationException was unhandled” and I don't know how
[英]I keep getting this error message and I don't know why
錯誤信息是:
“_djv.Authenticator”不包含“authenticate”的定義,並且找不到接受“_djv.Authenticator”類型的第一個參數的擴展方法“authenticate”(您是否缺少 using 指令或程序集引用?)我的代碼在下面,我有一個控制台應用程序和一個名為身份驗證器的類,兩段代碼都在那里。
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
類。 如果您沒有明確指定命名空間,則將使用當前命名空間中的類(在這種情況下是錯誤的)。
您可以通過以下方式解決:
顯式創建正確類的實例
var auth = new _Authenticator.Authenticator()
例如,將您的主類重命名為其他名稱Main
。
我強烈推薦選項 2,以防止進一步混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.