假设我创建了一个类名"CharacterStat“,它的成员包括health、attack、moveSpeed……并且我覆盖了类的运算符"+,-“。后来,我添加了更多的成员,如装甲和灵巧。有没有办法检查我没有忘记在+,-运算符中实现它们?
发布于 2019-04-03 14:12:49
如果您担心错过向operator+添加新统计信息,并且所有统计信息都属于同一类型,请生成代码而不是编写代码。如果您将其放入.tt文件中(并确保将其的“自定义工具”属性设置为TextTemplatingFileGenerator
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
namespace Abc
{
public class CharacterStat{
<# GenerateBasicStats("attack","health","moveSpeed"); #>
}
}
<#+
public void GenerateBasicStats(params string[] statNames)
{
//Readonly props
foreach(var name in statNames){
WriteLine("public int {0} {{get;}} ",name);
}
//Constructor
Write("public CharacterStat(");
bool first = true;
foreach(var name in statNames){
if(!first) Write(", ");
first = false;
Write("int {0}",name);
}
WriteLine(")");
WriteLine("{");
foreach(var name in statNames){
WriteLine("this.{0} = {0};",name);
}
WriteLine("}");
//Operator+
WriteLine("public static CharacterStat operator+(CharacterStat left, CharacterStat right)");
WriteLine("{");
Write("return new CharacterStat(");
first = true;
foreach(var name in statNames)
{
if(!first) Write(", ");
first = false;
Write("left.{0} + right.{0}",name);
}
WriteLine(");");
WriteLine("}");
}
#>我们生成这个类:
namespace Abc
{
public class CharacterStat
{
public int attack { get; }
public int health { get; }
public int moveSpeed { get; }
public CharacterStat(int attack, int health, int moveSpeed)
{
this.attack = attack;
this.health = health;
this.moveSpeed = moveSpeed;
}
public static CharacterStat operator +(CharacterStat left, CharacterStat right)
{
return new CharacterStat(left.attack + right.attack, left.health + right.health, left.moveSpeed + right.moveSpeed);
}
}
}(好吧,没有那么漂亮,但它可以被清理)。现在你不会忘记了,因为添加一个新的stat是在一个地方完成的,它确保它有一个属性,包含在构造函数中,并由operator+覆盖。
发布于 2019-04-03 13:50:33
不,没有内置的支持来检查“一个类的所有字段是否都在一个给定的方法中使用”。
您的选择:
operator +进行良好的单元测试以使用反射,并显式地收集所有需要进行IL解析器的字段的信息,以便深入研究operator+代码的编译实现,并希望它是以相对重复的方式编写的,以便您能够理解IL。https://stackoverflow.com/questions/55486981
复制相似问题