我正在学习C#,我询问了这个类之外与类的变量交互的最佳方法。我想了想:
public class Character
{
private int x, y;
public Character(int posX, int posY)
{
x = posX;
y = posY;
}
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
y = value;
}
}
}`
class MainClass
{
public static void Main (string[] args)
{
Character hero = new Character (42, 36);
Console.WriteLine (hero.X);
Console.WriteLine (hero.Y);
hero.X = 5;
Console.WriteLine (hero.X);
}
}我不知道这个方法是好的还是优化的,但它是有效的。但是,如果我想对10个变量这样做,我的类将为我的变量做至少100行(如果我想在get/set中添加测试)100行……你知道还有什么方法可以继续吗?或者我如何压缩这个方法?谢谢!
发布于 2017-01-23 18:04:09
除了auto-properties之外,还可以使用Object initializer。在这种情况下,您不需要显式声明构造函数。使用该功能,您可以节省更多代码行。检查以下代码以查看更改:
public class Character
{
public int X { get; set; }
public int Y { get; set; }
}
class MainClass
{
public static void Main (string[] args)
{
var hero = new Character {X = 42, Y = 36};
Console.WriteLine(hero.X);
Console.WriteLine(hero.Y);
hero.X = 5;
Console.WriteLine (hero.X);
}
}https://stackoverflow.com/questions/41802904
复制相似问题