简体   繁体   中英

Setting up a Styling Class in C#

I have a class called Themes which keeps track of colors to be used in other classes. The class contains various different colors which changes depending on the day.

public class Themes
    var textColor;
    var contentColor;

    updateTheme()
    {
        updates colors
    }

There are 2 ways in my mind that I can access the fields.

theme = new Theme()
textColor = theme.textColor  

or

theme = new Theme()
textColor = theme.GetTextColor() 

The style class has at least 20 fields. I know both ways work, I'm wondering which would be better code practice. (Would it be considered ok to expose these fields and set them all as public? or write 20 GetMethods?)

You could use the first way (which appears to be using a property), but personally, I might do something like this.

public enum ThemeColor
{
    TextColor,
    BackgroundColor,
    // Etc.
}

public ??? GetColor(ThemeColor color)
{
    // Return the requested color here
}

While this is a little more verbose.

textColor = theme.GetColor(ThemeColor.TextColor);

It could make your implementation more simple. For example, maybe your colors are stored in an array or a List<> . So you could just convert the enum to an integer that efficiently serves as an index into your array. Much simpler that writing twenty methods or properties.

I also find this approach quite readable.

The language feature you should use is properties. These syntactically look like fields to consuming code, but you can implement custom logic for getting or setting values in the implementation. You can also restrict them to be readonly or writeonly (very uncommon).

See the Microsoft C# programming guide: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

Syntax is like this to write:

public class Foo {

    public Foo(int bar, string baz) {
        Bar = bar;
        Baz = baz;
    }

    public int Bar { get; set; } //Read/write property

    public string Baz { get; } //Readonly

    public bool IsFooEven {
       get { return Bar % 2 == 0; } //Calculated property
    }
}

Consumers would just see this:

var foo = new Foo(5, "abc");

var bar = foo.Bar; //returns 5

var baz = foo.Baz; //returns "abc"

foo.Baz = "xyz"; //sets value

Properties are actually implemented as a get_Bar() and set_Bar(int value) method around a field in the compiled assembly, but C# makes them nicer to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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