Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic classes C# constructor OOP
    primarykey
    data
    text
    <p>I am new to OOP and I think I don't understand static classes.</p> <p>I want to create a static class Actions and one static method for changing textblock apperance..</p> <p>Here is my code:</p> <pre><code>public static class Tools { public enum StatusOption { Online, Offline, Warning } } public class Actions { private SortedDictionary&lt;Tools.StatusOption,SolidColorBrush&gt; StatusColors = new SortedDictionary&lt;Tools.StatusOption,SolidColorBrush&gt;(); public Actions() { StatusColors.Add(Tools.StatusOption.Online, new SolidColorBrush(Colors.Green)); StatusColors.Add(Tools.StatusOption.Offline, new SolidColorBrush(Colors.Red)); StatusColors.Add(Tools.StatusOption.Warning, new SolidColorBrush(Colors.Orange)); } public void SetStatus(Tools.StatusOption _statusOption, TextBlock _txtBlock) { _txtBlock.Text = _statusOption.ToString(); _txtBlock.Foreground = StatusColors[_statusOption]; } } </code></pre> <p>It works, but I have to create several instances of my class, which is IMHO useless.</p> <pre><code>private void Close_Click(object sender, RoutedEventArgs e) { Actions a1 = new Actions(); a1.SetStatus(Tools.StatusOption.Offline, StatusTextBlock); } private void Open_Click(object sender, RoutedEventArgs e) { Actions a2 = new Actions(); a2.SetStatus(Tools.StatusOption.Online, StatusTextBlock); } </code></pre> <p>I would prefer it just like this:</p> <pre><code>private void Open_Click(object sender, RoutedEventArgs e) { Actions.SetStatus(Tools.StatusOption.Online, StatusTextBlock); } </code></pre> <p>I know, I have to define a static class and static constructor:</p> <pre><code>public static class Actions { private SortedDictionary&lt;Tools.StatusOption,SolidColorBrush&gt; StatusColors = new SortedDictionary&lt;Tools.StatusOption,SolidColorBrush&gt;(); static Actions() { StatusColors.Add(Tools.StatusOption.Online, new SolidColorBrush(Colors.Green)); // .... } } </code></pre> <p>The problem is, I can not access to private member StatusColors in static constructor, and I can not create instance of StatusColors.</p> <p>Any Ideas how to solve it?</p> <p>Thanks. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload