简体   繁体   English

C#在运行时将只读变量添加到类中

[英]C# Adding readonly variables into a class during run time

I'm trying to find a way to add colors to a "palette". 我正在尝试找到一种向“调色板”添加颜色的方法。 The worst part of not learning computer science is that it is hard to word questions. 不学习计算机科学的最糟糕的部分是很难说出问题。 I've been searching for adding enumerations in a class during run time. 我一直在寻找在运行时在类中添加枚举的方法。 Because ideally, I can do a Console.ReadLine() to add a new color. 因为理想情况下,我可以执行Console.ReadLine()来添加新颜色。

class Program
{
    static void Main(string[] args)
    {
        Color _Color = new Color();

        Console.WriteLine(Palette.Black);
        // _Color.addColor(Console.ReadLine(), Console.ReadLine());
        Console.ReadKey();
    }
}

public class Palette
{
    private readonly string color;
    public static readonly Palette Black = new Palette("black");
    public static readonly Palette Red = new Palette("red");
    public static readonly Palette Green = new Palette("green");
    public static readonly Palette Blue = new Palette("blue");

    //I want to be able to create new colors by using the Color.addColor() method

    private Palette(string inputColor) { this.color = inputColor; }
    public override string ToString() { return this.color; }
}

public class Color
{
    public void addColor(string colorName, string color) 
    {
        //create a new color into Palette using form:
        // public static readonly Palette colorName = new Palette("color");
    }
}

I want to be able to do Console.WriteLine(Palette.Yellow) after inputting into the Console that I want to add the color yellow into the palette. 输入到控制台后,我想能够将Console.WriteLine(Palette.Yellow)添加到控制台中,以便将黄色添加到调色板中。

I think you should start with maybe redesigning your application to use a collection of colors instead of fields on palette. 我认为您应该从重新设计应用程序开始,以使用颜色的集合而不是调色板上的字段。 However you might be able to achieve what you're looking for with ExpandoObject . 但是,您可以使用ExpandoObject实现所需的功能 I found it from a different article here . 我在这里的另一篇文章中找到了它。

C# is not designed in a way for you to dynamically create variables. C#并不是以一种动态创建变量的方式设计的。 Like @skalpin said, a redesign in pretty much the only solution for you. 就像@skalpin所说的那样,重新设计几乎是您的唯一解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM