简体   繁体   中英

how to create properties with sub properties having constant values in a class using c#

I would like to create a string using the StringBuilder() class. I have a collection of records of say Employees. Each record of Employee has columns such as firstName, lastName, city, etc. The string that I want to create will have the values of the above mentioned columns each. For this I need to create a class

class Columns
{
    string Firstname
    {
        startPosition = 1;
        length = 32;
    }

    string LastName
    {
        startPosition = 33;
        length = 32;
    }
}

In the string that I'm building I need to insert the values of Firstname,Lastname in the respective start positions mentioned. I'm new to this and I need help in creating the above class. The above specified code is just the prototype of what the class should be like but I do not know how exactly to create this. I need the properties startPosition and length to be present in all the columns and these values need to be hardcoded. Sorry if my question is vague. Please help..

Let me start with telling you, there is no such thing as "sub properties". What you can do is have a property/field of a class which exposes properties itself.

Therefore, you might want to create a class for one Column and then create a List to keep track of your Columns like in the following example.

public class Column
{
    public string Name { get; set; }
    public int StartPos { get; set; }
    public int Length { get; set; }
}

public class Test
{
    private List<Column> Columns = new List<Column>();

    public Test()
    {
        this.Columns.Add(new Column { Name = "FirstName", StartPos = 1, Length = 32 });
        this.Columns.Add(new Column { Name = "LastName", StartPos = 33, Length = 32 });
    }

    public string GetThatString(string str)
    {
        foreach (var col in this.Columns)
        {
            // Do what you need. Sample:
            var item = str.Substring(col.StartPos, col.Length);
            Console.WriteLine("{0}: {1}", col.Name, item);
        }
    }
}

You could then iterate over the items in the List and have your string builder do the work yo need. Of course, you could also create a property for each Column instead of a List of all the Columns.

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