[英]What is the conventional way to assign default values to member variables in C#?
[英]C# : How to assign and retrieve values into member variables of BASE class
我是初学者。 我正在尝试编写一个具有颜色类的程序,该类可以执行各种操作(红色,绿色,蓝色和alpha值)以获取颜色的灰度值。 但是我不知道如何为基类的成员变量赋值。
首先,我创建一个构造器,它接受像这样的红色,蓝色,绿色和alpha值
private byte red;
private byte green;
private byte blue;
private byte alpha;
public Color(byte red, byte green, byte blue, byte alpha)
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
然后我声明一个颜色变量(我希望人们能够输入该值)
Color color = new Color(
Convert.ToByte(
Console.ReadLine()
), Convert.ToByte(
Console.ReadLine()
), Convert.ToByte(
Console.ReadLine()
), 255
);
这样对吗? 将红色变量分配给用户输入的值吗?
如果正确,我该如何在用户输入之前询问用户?
例如,在他们输入红色值之前,我会问他们:
输入您的红色值
那我问他们
输入您的绿色值
他们继续输入自己的值,...等等...
另一个问题:我还想在颜色类中创建方法以从颜色对象中获取(检索)红色,绿色,蓝色值。 我创建了它们,但不知道是否正确。 你能帮我检查一下吗?
public byte Getred(byte red)
{
return red;
}
public byte Getgreen(byte green)
{
return green;
}
public byte Getblue (byte blue)
{
return blue;
}
public byte Getalpha(byte alpha)
{
alpha = 255;
return alpha;
}
您可以使用Console.WriteLine
向用户显示提示消息并从用户那里接收输入。
Console.WriteLine("Please enter your red value: ");
byte redValue = Convert.ToByte(Console.ReadLine());
Console.WriteLine("Please enter your green value: ");
byte greenValue = Convert.ToByte(Console.ReadLine());
Console.WriteLine("Please enter your blue value: ");
byte blueValue = Convert.ToByte(Console.ReadLine());
Color color = new Color(redValue, greenValue, blueValue, 255);
如果希望它们是私有的,并且仅通过特定方法公开它们,则获取值的方法是正确的。
编辑:
如果您只想允许在类中更改类字段,但只允许其他调用者获取值而不设置值,则可以使用属性,这样可以避免编写那些get
方法。
public class Color
{
public byte Red { get; private set; }
public byte Green { get; private set; }
public byte Blue { get; private set; }
public byte Alpha { get; private set; }
public Color(byte red, byte green, byte blue, byte alpha)
{
this.Red = red;
this.Green = green;
this.Blue = blue;
this.Alpha = alpha;
}
}
Color color = new Color(100, 100, 100, 255);
byte redValue = color.Red;
color.Red = 0; // Error, cannot set value outside the class.
对于C#,您可以使用属性代替getmethod等方法
class MyColor
{
private byte red;
private byte green;
private byte blue;
private byte alpha;
public MyColor(byte red, byte green, byte blue, byte alpha)
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
public byte Red
{
get
{
return this.red;
}
}
}
class Program
{
static void Main(string[] args)
{
byte red;
while (true)
{
Console.WriteLine("Input a byte in the range of 0 to 255 - for Red:");
string line = Console.ReadLine();
if (line.Length > 3 || !byte.TryParse(line, out red))
{
Console.WriteLine("Invalid Entry - try again");
Console.WriteLine("Input a byte in the range of 0 to 255 - for Red:");
}
else
{
break;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.