简体   繁体   中英

Constants best practices

I have a simple classes which are initialized with dictionary values and can return its values as dictionary, here is an example:

public class ApartmentModel
{
    public int Id { get; set; }

    public string Title { get; set; }

    public ApartmentModel()
    {
    }

    public ApartmentModel(IDictionary<string, object> item)
    {
        Id = (int)item["ID"];
        Title = item["Title"].ToString();           
    }

    public override IDictionary<string, object> FieldsValues()
    {
        var item = new Dictionary<string, object>
        {
            ["ID"] = Id,
            ["Title"] = Title                
        };
        return item;
    }
}

Some classes have common fields, like "Id" and "Title". I'm wondering what is the best practice to store dictionary keys strings as constants: in the same class as private fields or in the settings/resource file?

It looks like the values of your constants correspond to property names. In situations like that it is best not to use string literals at all, replacing with nameof operator (assuming that C# 6 language is in use)

public ApartmentModel(IDictionary<string, object> item)
{
    Id = (int)item[nameof(Id)];
    Title = item[nameof(Title)].ToString();           
}

public override IDictionary<string, object> FieldsValues()
{
    var item = new Dictionary<string, object>
    {
        [nameof(Id)] = Id,
        [nameof(Title)] = Title                
    };
    return item;
}

An even better approach is to not code these methods directly, replacing them with a single method based on reflection and custom attributes. Define an attribute that designates a property for inclusion in FieldsValues - generated IDIctionary , and write a single helper method that walks your object's class hierarchy, finds all attributes with the custom attribute, and produces / consumes a dictionary based on them.

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