[英]How can I use a class and constructor in a another class, method and store them to my list? C#
How can I use a class and constructor in a another class and method?如何在另一个 class 和方法中使用 class 和构造函数? I would like to be able to have a menu in the main method and add names to my list via the method Add_them().
我希望能够在主方法中有一个菜单,并通过 Add_them() 方法将名称添加到我的列表中。
One of the errors is that the name does not exist in the current context错误之一是该名称在当前上下文中不存在
using System;
using System.Collections.Generic;
using System.Linq;
namespace test
{
class Poll
{
public string Name { get; set; }
public Poll(string name)
{
this.Name = name;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Menu");
Console.WriteLine("Enter number for the option you want");
Console.WriteLine("1. Add names");
Console.WriteLine("2. Stop program");
var polls = new List<string>();
string userChoice = Console.ReadLine();
int userNumber;
int.TryParse(userChoice, out userNumber);
if (userNumber == 1)
{
Add_them(polls);
}
else if (userNumber == 2)
{
End_it();
}
}
static void Add_them(List<string> polls)
{
string u = null;
do
{
Poll poll1 = new Poll(string name); // ERROR
Console.WriteLine("Name:");
poll1.Name = Console.ReadLine();
Console.WriteLine("Write end to stop or enter and continue on");
u = Console.ReadLine();
polls.Add();
} while (u != "end");
}
static void End_it()
{
System.Environment.Exit(1);
}
}
}
This line: Poll poll1 = new Poll(string name);
这一行:
Poll poll1 = new Poll(string name);
needs to be changed to actually use a string, a string is anything inside double quotes ""
so for example:需要更改为实际使用字符串,字符串是双引号
""
内的任何内容,例如:
Poll poll1 = new Poll("Poll1");
if you want to set it to an empty value then the string class has a static member called Empty
:如果要将其设置为空值,则字符串 class 有一个名为
Empty
的 static 成员:
Poll poll1 = new Poll(string.Empty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.