C# : How to assign and retrieve values into member variables of BASE class

标签 c#

我是初学者。我正在尝试编写一个程序,它有一个颜色类,可以执行各种操作(红色、绿色、蓝色和 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
);

是吗?红色变量会被赋值给用户输入的值吗?

如果正确,我如何在用户输入之前询问用户?
例如,在他们输入红色值之前,我会问他们:

input your red value

那我去问他们

input your green value

然后他们继续输入他们的值,...等...

另一个问题:我还想在颜色类中创建方法来从颜色对象中获取(检索)红色、绿色、蓝色值。我创建了它们,但我不知道它是否正确。你能帮我检查一下吗?

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);

如果您希望它们是私有(private)的,并且仅通过特定方法公开它们,那么您获取这些值的方式是正确的。

编辑:

如果您只想允许从类内部更改类字段,但允许其他调用者仅获取值而不是设置它,那么您可以使用属性,这将使您不必编写那些 获取方法。

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# : How to assign and retrieve values into member variables of BASE class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657440/

相关文章:

c# - C# .NET 中部分文档的 Xml 签名验证失败

c# - 使用 LINQ/C# 使用 JSON 内容

c# - 在 Type.GetType(..) == null 上抛出什么?

c# - 从 StringBuilder 中删除连续的空白行

c# - 什么时候应该使用 public、private 或 [SerializeField]?统一 C#

c# - 为什么字符串 IndexOf() 不区分大小写?

c# - 抽象属性的 MVC 属性

c# - MVVM 模式中的 WPF DataBinding ListBox

C# WPF,日期选择器验证

c# - 如何阻止 IIS 上的 WCF 服务变为空闲