2015-07-28 5 views
1

Я пытаюсь создать программу менеджеров контактов, используя список для хранения и отображения данных. Мне нужно просмотреть отчет, в котором отображается сводка доступных контактов, а затем есть меню, позволяющее пользователю взаимодействовать с программой. У меня есть метод для создания списка с данными и метода для создания нового контакта, но мой метод createContact() продолжает получать ошибку: Тип или имя пространства имен «ContactTypes» не удалось найти (вам не хватает директивы using или ссылка на сборку?). Я не уверен, как это исправитьТип или имя пространства имен '' не удалось найти

Любое руководство будет оценено

static void Main(string[] args) 
    {   
     //Declare the list 

     List<Contact> contactList = new List<Contact>(); 

     //Main Driver 
     char menuItem; 
     Console.WriteLine("Contact List\n"); 
     menuItem = GetMenuItem(); 
     while (menuItem != 'Q') 
     { 

      ProcessMenuItem(menuItem, contactList); 
      menuItem = GetMenuItem(); 

     } 
     Console.WriteLine("\nThank you, goodbye"); 
     Console.ReadLine(); 
    } 
    //Returns either a 'C', 'R', 'U', 'D', 'L', or 'X' to the caller 
    static char GetMenuItem() 
    { 
     char menuItem; 
     DisplayMenu(); 
     menuItem = char.ToUpper(IOConsole.GetChar("\nPlease pick an item: ")); 
     while (menuItem != 'C' 
      && menuItem != 'R' && menuItem != 'Q' && menuItem != 'U' && menuItem != 'D' && menuItem != 'S' && menuItem != 'L' && menuItem != 'F' && menuItem != 'P' && menuItem != 'T') 
     { 
      Console.WriteLine("\nError - Invalid menu item"); 
      DisplayMenu(); 
      menuItem = char.ToUpper(IOConsole.GetChar("\nEnter option or M for menu:")); 
     } 
     return menuItem; 
    } 

    static void DisplayMenu() 
    { 
     Console.WriteLine("C-> Create Contacts"); 
     Console.WriteLine("R-> Remove Contacts"); 
     Console.WriteLine("U-> Update Contacts"); 
     Console.WriteLine("D -> Load data from file"); 
     Console.WriteLine("S-> Save data to file"); 
     Console.WriteLine("L-> View sorted by last name"); 
     Console.WriteLine("F-> View sorted by first name"); 
     Console.WriteLine("P-> View by partial name search"); 
     Console.WriteLine("T-> View by contact type"); 
     Console.WriteLine("Q-> Quit"); 
    } 

    //Routes to the appropriate process routine based on the user menu choice 
    static void ProcessMenuItem(Char menuItem, List<Contact> contactList) 
    { 
     switch (menuItem) 
     { 
      case 'C': 
       createContact(); 
       break; 
      case 'R': 
       removeContact(contactList); 
       break; 
      case 'U': 
       updateContact(contactList); 
       break; 
      case 'D': 
       LoadFromFile(); 
       break; 
      case 'S': 
       saveToFile(); 
       break; 

      case 'L': 
       sortByLastName(contactList); 
       break; 
      case 'F': 
       sortByFirstName(contactList); 
        break; 
      case 'P': 
        DisplayList(contactList); 
        break; 
      case 'T': 
        sortByContactType(); 
        break; 
      case 'Q': 

        break; 

     }     
    } 

    public static void createContact() 
    { 
     Contact c1 = new Contact(); 
     try { 
     Console.WriteLine("\nGetFirstName"); 
     c1.GetFirstName = Console.ReadLine(); 
      } 
     catch (System.NullReferenceException) 
     { 
      Console.WriteLine("Player create failed"); 
     } 
     Console.WriteLine("\nGetLastName"); 
     c1.GetLastName = Console.ReadLine(); 
     Console.WriteLine("\nGetEmailAddress"); 
     c1.GetEmailAddress = Console.ReadLine(); 
     Console.WriteLine("\nGetPhoneNumber"); 
     c1.GetPhoneNumber = Console.ReadLine(); 
     Console.WriteLine("\nContactTypes"); 
     //ERROR LINE// 
     c1.ContactTypes = (ContactTypes)Enum.Parse(typeof(ContactTypes), Console.ReadLine(), true); 

     //Create more contacts... 

     //Add all contacts here 
     ContactCollection contactList = new ContactCollection(); 
     contactList.Add(c1); 

     //Loop through list 
     foreach (Contact c in contactList) 
     { 

      Console.WriteLine(c.GetFirstName); 
      Console.WriteLine(c.GetLastName); 
      Console.WriteLine(c.GetEmailAddress); 
      Console.WriteLine(c.GetPhoneNumber); 
      Console.WriteLine(c.ContactTypes); 

     } 

     Console.ReadLine(); 

    } 

Here is my contact class if needed

class Contact 
{ 

    //private member variables 
    private String _firstName; 
    private String _lastName; 
    private ContactTypes _contactTypes; 
    private String _phoneNumber; 
    private String _emailAddress; 




    //Public constructor that takes five arguments 
    public Contact() 
    { 
     //Call the appropriate setter (e.g. FirstName) to set the member variable value 
     /*GetFirstName = firstName; 
     GetLastName = lastName; 
     ContactTypes = contactTypes; 
     GetPhoneNumber = phoneNumber; 
     GetEmailAddress = emailAddress;*/ 

    } 


    /********************************************************************* 
    * Public accessors used to get and set private member variable values 
    *********************************************************************/ 
    //Public ContactTypes accessor 
    public ContactTypes ContactTypes 
    { 
     get 
     { 
      //Return member variable value 
      return _contactTypes; 
     } 
     set 
     { 
       //Validate value and throw exception if necessary 
      if (value == null) 
       throw new Exception("ContactType must have a value"); 
      else 
       //Otherwise set member variable value*/ 
       _contactTypes = value; 
     } 
    } 
    enum ContactTypes { Family, Friend, Professional } 
    //Public FirstName accessor: Pascal casing 
    public String GetFirstName 
    { 
     get 
     { 
      //Return member variable value 
      return _firstName; 
     } 
     set 
     { 
      //Validate value and throw exception if necessary 
      if (value == "") 
       throw new Exception("First name must have a value"); 
      else 
       //Otherwise set member variable value 
       _firstName = value; 
     } 
    } 

    //Public LastName accessor: Pascal casing 
    public String GetLastName 
    { 
     get 
     { 
      //Return member variable value 
      return _lastName; 
     } 
     set 
     { 
      //Validate value and throw exception if necessary 
      if (value == "") 
       throw new Exception("Last name must have a value"); 
      else 
       //Otherwise set member variable value 
       _lastName = value; 
     } 
    } 



    //Public PhoneNumber accessor 
    public String GetPhoneNumber 
    { 
     get 
     { 
      //Return member variable value 
      return _phoneNumber; 
     } 
     set 
     { 
      bool isValid = Regex.IsMatch(value, @"/d{3}-/d{3}-/d{4}"); 
      //Validate value and throw exception if necessary 
      if (value == "") 
       throw new Exception("PhoneNumber must have a value"); 
      else 
       //Otherwise set member variable value 
       _phoneNumber = value; 
     } 
    } 



    //Public Email accessor 
    public String GetEmailAddress 
    { 
     get 
     { 
      //Return member variable value 
      return _emailAddress; 
     } 
     set 
     { 
      //Validate value and throw exception if necessary 
      if (value == "") 
       throw new Exception("EmailAddress must have a value"); 
      else 
       //Otherwise set member variable value 
       _emailAddress = value; 
     } 
    } 

} 
+1

У вас есть свойство, называемое 'ContactTypes', которое конфликтует с типом одного и того же имени в нескольких местах. Вы можете обратиться к типу с помощью 'global :: ContactTypes' (или заменить' global' пространством имен этого типа). –

+1

Переместите enum 'ContactTypes' вне сферы действия класса Contact и установите его видимость как' public' – HashPsi

+0

Рассмотрите свой код, позвольте мне добавить, что свойство 'GetPhoneNumber' задано для проверки его значений с помощью:' bool isValid = Regex. IsMatch (значение, @ "/ d {3} -/d {3} -/d {4}"); 'но вы не используете' isValid', вы можете добавить другое 'else if (! isValid) {// сделать что-то}'. –

ответ

0

У вас не хватает using directive к ContactTypes «s пространство имен.

Проверьте пространство имен Contact класс (видимо, ContactTypes также имеет такое же пространство имен). Например, если это namespace ContactTypesNamesapce

Добавьте в свой основной класс, который имеет основной метод. Например: using ContactTypesNamespace;

Смежные вопросы