[英]Set Color to Variable for later use in c#
i try to store a Color to a variable that i can use later without providing RGB informations twice: 我尝试将Color存储到一个变量中,以便以后可以使用,而无需两次提供RGB信息:
Code: 码:
public partial class Form1 : Form
{
public Color Color1 = new Color();
public Color Color2 = new Color();
public Form1 ()
{
InitializeComponent();
Color1 = Color.White;
Color2 = Color.FromArgb(255, 112, 114);
}
private void LoadSomething()
{
//not working - but dont know why
TreeNode TreeNode1 = new TreeNode();
TreeNode1.ForeColor = Color1;
TreeNode1.BackColor = Color2;
//working
TreeNode TreeNode1 = new TreeNode();
TreeNode1.ForeColor = Color.White;
TreeNode1.BackColor = Color.FromArgb(255, 112, 114);
}
}
Can someone tell me why its not working in the first way? 有人可以告诉我为什么它不能首先起作用吗? thx
谢谢
The reason could be as follows: 原因可能如下:
You call your method befor construcotr of Form1
is called. 您可以在调用
Form1
construcotr之前调用您的方法。 This way, color objects are instantiated, but in constructor you pass object with actual colors specified. 这样,实例化了颜色对象,但是在构造函数中,您传递了具有指定实际颜色的对象。 Thus, before constructor is called, you have "blank" colors, after constructor is called, you have white and the other color.
因此,在调用构造函数之前,您具有“空白”颜色,在调用构造函数之后,您具有白色和另一种颜色。
So, if you call LoadSomething
before constructor is called, the first approach won't work. 因此,如果在调用构造
LoadSomething
之前调用LoadSomething
,则第一种方法将行不通。 The second, directly specifies color, so it will always work. 第二,直接指定颜色,因此它将始终有效。
But to be sure, you should share code, where you call LoadSomething
. 但是可以肯定的是,您应该共享代码,在其中调用
LoadSomething
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.