简体   繁体   English

C#:通过变量引用类

[英]C#: Referencing Classes by a Variable

I'm trying to get the hang of using variables in C#, but have hit a roadblock. 我试图在C#中使用变量,但是遇到了障碍。 The following doesn't work. 以下不起作用。

public static void SetBG(string s)
{
    Console.BackgroundColor = ConsoleColor.s;
}

A very simple method that should set the console's background color according to what the programmer sent through the s variable. 一个非常简单的方法,应根据程序员通过s变量发送的内容设置控制台的背景颜色。 If I used SetBG("Red"); 如果我使用SetBG("Red"); , it should go through, but it doesn't. ,它应该通过,但它不会。 This is because System.ConsoleColor' does not contain a definition for 's' . 这是因为System.ConsoleColor' does not contain a definition for 's'

How can I do this in C#? 我怎么能在C#中做到这一点?

This is not the correct way to do this, and it looks like there are two main concepts you're having trouble with, and understanding them will help you do this correctly. 这不是正确的方法,看起来你有两个主要概念,理解它们将帮助你正确地做到这一点。

Firstly, s is a variable in your current class. 首先, s是当前类中的变量。 ConsoleColor.s would refer to the s variable in the ConsoleColor class (it does not have one, hence your error). ConsoleColor.s会引用ConsoleColor类中的s变量(它没有一个,因此你的错误)。 This is called scope , or encapsulation , and allows us to reuse common words/names without conflict. 这称为范围封装 ,允许我们重用常见的单词/名称而不会发生冲突。

Secondly, your code will be compiled before it is run, and ConsoleColor.s (assuming there was such a thing) would no longer say ConsoleColor.s . 其次,您的代码将在运行之前进行编译,而ConsoleColor.s (假设有这样的东西)将不再说ConsoleColor.s Instead, it would point to a place in memory where a value is stored representing "s". 相反,它将指向存储器中存储表示“s”的值的位置。 The s being passed to your method will be a string, such as "Red" or "Blue". 传递给您的方法的s将是一个字符串,例如“Red”或“Blue”。 There is no connection between such a string and a slot in memory for a differnt object to store it's values. 这样的字符串和内存中的插槽之间没有连接,以便不同的对象存储它的值。

To do what you are trying to do, you need to take the name of the color and translate it into a color. 要执行您要执行的操作,您需要获取颜色的名称并将其转换为颜色。 One way to do this would be with a series of if / else statements checking the contents of the string and assigning the appropriate color if it matches a color name. 一种方法是使用一系列if / else语句检查字符串的内容,并在匹配颜色名称时指定适当的颜色。
Fortunately, there is an easier way. 幸运的是,有一种更简单的方法。 You can simply parse the string into a ConsoleColor ! 您可以简单地将字符串解析为ConsoleColor

Following the example from MSDN you can do this: 按照MSDN中的示例,您可以执行以下操作:

Console.BackgroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), s);
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof (ConsoleColor), s);

ConsoleColor is an enum. ConsoleColor是一个枚举。 You'll have to cast s . 你必须投s

public static void SetBG(string s){
   Console.BackgroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), s);
}

This is because ConsoleColor is an enumeration, try 这是因为ConsoleColor是枚举,请尝试

 Console.BackgroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), s);

You should consider handling if the string is not valid (eg s="Ship") with something like this 如果字符串无效(例如s =“Ship”),你应该考虑处理这样的事情

 ConsoleColor colorValue;
 if (Enum.TryParse(s, out colorValue))
 {        
     Console.BackgroundColor = colorValue;
 }
ConsoleColor colour;
if (ConsoleColor.TryParse(s, out colour))
{
   Console.BackgroundColor = colour;
}

Just to add to everyone else's use of the Enum.Parse method , as of .NET 4.0 you can use the Enum.TryParse generic method to better handle invalid values: 只是为了添加其他人对Enum.Parse方法的使用,从.NET 4.0开始,您可以使用Enum.TryParse泛型方法来更好地处理无效值:

public static void SetBG(string s)
{
    ConsoleColor color;

    if (!Enum.TryParse<ConsoleColor>(s, out color))
        throw new ArgumentException("s");

    Console.BackgroundColor = color;
}

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

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