简体   繁体   English

将“颜色”设置为“变量”以供以后在c#中使用

[英]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.

相关问题 将DataGridView单元格BackColor传递给变量,以供以后在C#中使用 - Pass DataGridView cell BackColor to variable for later use in c# 在 C# 中,为什么我不能使用其地址填充局部变量,然后再使用该变量? - In C#, why can't I populate a local variable using its address, then use the variable later? C#将变量标记为null以便稍后返回 - C# labelling a variable as null to later return C# 变量[#] in if 语句中 # 将在后面给出 - C# variable[#] in if statement where the # will be given later rangevalidator C#如何稍后在代码中使用 - rangevalidator c# how to use later in code 保存用户输入以供以后使用C# - Save User Inputs for Later Use C# “存储”一个类型参数供以后在C#中使用? - “Store” a type parameter for later use in C#? c#如何将selectedItems(listview)复制到变量中,然后在ListView中使用它(复制和粘贴)FileExplorer - c# how to copy the selectedItems (listview) into a variable then use it later (copy & paste) FileExplorer in ListView 如何使用 ASP.NET C# 将 SQL 查询的结果存储在会话变量中以便以后使用 - How to store the result of SQL query in Session Variable using ASP.NET C# to use it later 通过c#中的颜色代码设置颜色 - Set color through color code in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM