我正在尝试创建一个表示报告文件的简单类。我希望将字符串追加到报告文件中(字符串将存储在类中,但不会在每个追加时写入)。覆盖+
运算符是否有效,以便它将字符串作为参数并返回Report
对象?
例如;
// Is this valid code? If not how can I achieve this?
public Report operator + (string text)
{
fileContents.Append(text);
}
目前,此方法会给编译器错误:
一元运算符的参数必须是包含类型
预期用途:
Report r = new Report("myUniqueReport");
r += "Some line of text";
.. peform unrelated logic
r.write();
完整课程:
class Report
{
protected StringBuilder fileContents = new StringBuilder();
public Report(string reportName)
{
// TODO: create file in current project dir or desktop with reportName but must be unique name
}
// Is this valid code?
public Report operator + (string text)
{
fileContents.Append(text);
}
public void write()
{
// todo write string builder to file
}
}
答案 0 :(得分:3)
在这种情况下,我不建议使用运算符重载。
从技术上讲,操作员可能看起来像这样:
public static Report operator + (Report report, string text)
{
report.fileContents.Append(text);
return report;
}
虽然用户定义的运算符可以执行任何计算,但是强烈建议不要实现产生除直观预期结果之外的结果的实现
请注意,运营商也令人困惑:
Report report1 = report + "string";
将更改report
的状态。如果我们想要阻止它,我们每次使用重载的运算符StringBuilder
时都需要创建一个新的报告副本+
。