c# - 重载运算符时如何放置 6 个值?但是值也可以在之后添加?
问题描述
好的,我知道这看起来很复杂。从代码开始,必须取 2 个字符串 2 个 int 数字并根据输入将它们粉碎在一起,然后输出结果,如下所示:
输入:戴夫 8 杰西卡 7
输出:戴夫和杰西卡 15
我用不同的方法尝试了很多次,但似乎都没有用:(
我尝试将 name1 或 name2 之类的字符串放入 DancerPoints 类,但我找不到与输入连接的方法,我的意思是它存在但无法获得输入。
我也尝试直接将值放入参数中,但它说运算符只能取 2 个值,但我需要 6 个!4 代表舞者,2 代表管理。
此时它只获取 firstdancer 的字符串和 int 并使用它,但我不知道如何添加 seconddancer 的值。
我正在为此工作 3 个晚上,我不知道还能做什么?:(
using System;
using System.Collections.Generic;
namespace Code_Coach_Challenge
{
class Program
{
// I tried putting values here with public but why that not workked I dont know :(
static void Main(string[] args)
{
string name1 = Console.ReadLine();
int points1 = Convert.ToInt32(Console.ReadLine());
string name2 = Console.ReadLine();
int points2 = Convert.ToInt32(Console.ReadLine());
DancerPoints dancer1 = new DancerPoints(name1, points1);
DancerPoints dancer2 = new DancerPoints(name2, points2);
DancerPoints total = dancer1 + dancer2;
Console.WriteLine(total.name);
Console.WriteLine(total.points);
}
}
class DancerPoints
{
public string name;
public int points;
// I tried putting values here no luck.error CS7036
public DancerPoints(string name, int points)
{
this.name = name;
this.points = points;
// I tried putting values here no luck.error CS7036
}
//overload the + operator
public static DancerPoints operator+ (DancerPoints n, DancerPoints p)
{
// I tried putting values here no luck.error CS7036
string name = n.name + " & " + n.name;
int points = p.points + p.points;
DancerPoints res = new DancerPoints(name, points);
return res;
}
}
}
解决方案
如果您希望程序做的只是
- 询问姓名1
- 求积分1
- 询问姓名2
- 求积分2
- 打印
{Name1} & {Name2} {Points1 + Points2}
string name1 = Console.ReadLine();
int points1 = Convert.ToInt32(Console.ReadLine());
string name2 = Console.ReadLine();
int points2 = Convert.ToInt32(Console.ReadLine());
string output = $"{name1} & {name2} {points1 + points2}"
Console.WriteLine(output);
只是简单的字符串连接。不需要任何花哨的类或运算符重载。
现在,如果你想扩展你的代码来一次做两个以上的人,那么
class Dancer
{
public string Name {get;set;}
public int Score {get;set;}
}
var dancers = new List<Dancer>
{
new Dancer { Name = "David", Score = 8 },
new Dancer { Name = "Jessica", Score = 7 },
new Dancer { Name = "Sally", Score = 6 },
}
var allNames = string.Join(" & ", dancers.Select(x => x.Name));
var totalScore = dancers.Sum(x => x.Score);
var output = $"{allNames} {totalScore}"
通过这个例子,你会得到
大卫 & 杰西卡 & 莎莉 21
同样,不需要运算符重载。将舞者一起“添加”到一个新的“舞者”对象中并没有真正的意义。
推荐阅读
- uml - 具有条件转移的有限状态机可以表示为马尔可夫链吗?
- html - 如何在 CSS 中的 :first-child 之后选择元素?
- java - 将带有额外字符串的意图从活动发送到选项卡片段
- reactjs - 模态是否强制重新渲染整个组件?
- sql - 如果 postgreSQL/Redshift 中的值为 null,则返回 0 的替代方法
- python - 从 Python 中的字符串中获取特定文本
- java - Collections.unmodifiableMap (和其他)是否违反了 SOLID 原则?
- ruby-on-rails - Rails 查询连接到内部表计数
- powerbi - Power BI DAX 按日期汇总和筛选
- r - update.packages 无法更新为旧版 R 构建的现有包