C# 在函数C之外使用变量

C# 在函数C之外使用变量,c#,function,variables,set,C#,Function,Variables,Set,我想创建一个使用函数外另一个变量的变量,如下所示: private void tb_TextChanged(object sender, TextChangedEventArgs e) { ... } TextStyle txtstyle = new TextStyle(new SolidBrush(Color.Red), null, FontStyle.Regular); // the variable private void tb_VisibleRangeChangedDelaye

我想创建一个使用函数外另一个变量的变量,如下所示:

private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
  ...
}

TextStyle txtstyle = new TextStyle(new SolidBrush(Color.Red), null, FontStyle.Regular); // the variable

private void tb_VisibleRangeChangedDelayed(object sender, EventArgs e)
{
  ...
}
private TextStyle myTextStyle
    {
        get
        {
            var colorName = "Red";

            if(!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["myColor"]))
            {
                colorName = ConfigurationManager.AppSettings["myColor"];
            }

            return new TextStyle(new SolidBrush(Color.FromName(colorName)), null, FontStyle.Regular);
        }
    }
我想用应用程序设置中的自定义颜色替换txtstyle中的Color.Red。如何实现这一点?

既然您已经在类作用域中声明了txtstyle,那么您可以从属于同一类的函数中访问它


我建议您阅读。

我将创建一个类似以下内容的私有财产:

private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
  ...
}

TextStyle txtstyle = new TextStyle(new SolidBrush(Color.Red), null, FontStyle.Regular); // the variable

private void tb_VisibleRangeChangedDelayed(object sender, EventArgs e)
{
  ...
}
private TextStyle myTextStyle
    {
        get
        {
            var colorName = "Red";

            if(!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["myColor"]))
            {
                colorName = ConfigurationManager.AppSettings["myColor"];
            }

            return new TextStyle(new SolidBrush(Color.FromName(colorName)), null, FontStyle.Regular);
        }
    }

您必须添加对System.Configuration的引用才能使其工作。

您可以通过以下方式访问设置:

TextStyle txtstyle = new TextStyle(new SolidBrush(Properties.Settings.Default["Color"]), null, FontStyle.Regular); // the variable 

你为什么要这样做?你不能声明变量并用你想要的值在构造函数中初始化它吗?为什么你提供了两个方法?是否要在每次函数调用中更改一次文本样式?我只是提供了一些方法来显示变量在它们之外。我要替换txtstyle中的Color.Red。。。好像是丢失了我想他是在问如何更换应用程序中的颜色settings@V4Vendetta-那不是我读的。我的理解是,颜色是从配置中初始化的,但他想在运行时更改颜色,而不是更改配置。我花了一段时间才完全理解他的问题,但据我所知,这正是他想要的。是的,但是由于Fischermaen发布的代码更短,我用了他的,这正是我想要的,而且很简单。