c#在屏幕上显示“输入1,添加商品,输入2,删除商品”
时间: 2024-02-18 19:04:30 浏览: 20
在C#中,可以使用Console.WriteLine()方法在屏幕上显示文本。要显示“输入1,添加商品,输入2,删除商品”,可以使用以下代码:
```
Console.WriteLine("输入1,添加商品,输入2,删除商品");
```
这将在控制台窗口中显示文本:“输入1,添加商品,输入2,删除商品”。
相关问题
C#新增“添加商品”和“删除商品”两个功能,程序建立好商品信息之后,在屏幕上显示“1 添加商品;2 删除商品”,根据输入1或者2,执行相应的功能
好的,我可以帮你解决这个问题。以下是实现此的 C# 代码示例:
```
using;
namespace ProductManagement
{
class Program
{
static void Main(string[] args)
{
// 商品列表
string[] products = new[0];
while (true)
{
显示菜单
Console.WriteLine("1 添加商品");
Console.WriteLine("2 删除商品");
// 获取用户输入
string input = Console.ReadLine();
if (input == "1")
{
// 添加商品
Console.WriteLine("请输入商品名称:");
string productName = Console.ReadLine();
// 扩展商品列表
Array.Resize(ref products, products.Length + 1);
products[products.Length - 1] = productName;
Console.WriteLine("商品添加成功!");
}
else if (input == "2")
{
// 删除商品
Console.WriteLine("请输入要删除的商品编号:");
for (int i = 0; i < products.Length; i++)
{
Console.WriteLine($"{i + 1} {products[i]}");
}
int index = int.Parse(Console.ReadLine()) - 1;
if (index >= 0 && index < products.Length)
{
// 缩小商品列表
for (int i = index; i < products.Length - 1; i++)
{
products[i] = products[i + 1];
}
Array.Resize(ref products, products.Length - 1);
Console.WriteLine("商品删除成功!");
}
else
{
Console.WriteLine("商品编号无效!");
}
}
else
{
Console.WriteLine("无效的操作!");
}
Console.WriteLine();
}
}
}
}
```
在上述代码中,我们使用了一个 `while` 循环来不断显示菜单和获取用户输入。如果用户输入了 `1`,则会提示用户输入商品名称,并将其添加到商品列表中;如果用户输入了 `2`,则会显示商品列表,并要求用户输入要删除的商品的编号,然后从商品列表中删除相应的商品。注意,在删除商品时,我们使用了 `Array.Resize` 方法来缩小商品列表。
希望这个代码示例可以帮助你解决问题。
C#在原有的类基础上动态添加字段显示
在C#中,类是静态的,意味着在编译时定义的。因此,无法直接在运行时添加新字段。但是,你可以使用反射来实现动态添加字段的效果。
以下是一个示例代码,可以动态添加字段并在控制台中显示:
```csharp
using System;
using System.Reflection;
namespace DynamicFieldExample
{
class Program
{
static void Main(string[] args)
{
// 创建一个对象
MyClass obj = new MyClass();
// 获取类型的字段信息
FieldInfo fieldInfo = typeof(MyClass).GetField("newField", BindingFlags.Instance | BindingFlags.NonPublic);
// 动态添加字段并设置值
fieldInfo.SetValue(obj, "Hello, World!");
// 显示字段值
Console.WriteLine(obj.newField);
}
}
class MyClass
{
public int field1;
public string field2;
// 定义一个动态添加的字段
private string _newField;
// 添加一个属性来访问新字段
public string newField
{
get { return _newField; }
set { _newField = value; }
}
}
}
```
在上面的代码中,我们使用反射获取了`MyClass`类中的私有字段`_newField`,并使用`SetValue`方法给它赋值。最后,我们可以通过`newField`属性来访问新添加的字段并将其显示在控制台中。