dimanche 23 décembre 2018

Is it possible to use class properties to give an integer that represents the sequence in that same class?

I'm using my class properties to store information at the moment. To make sure I can determine the right sequence (order) to fill the data using the class and an index, I was advised to use Attributes (property 0 will get index 0, etc). It works very well using the CallerLineNumber. This is my example:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class OrderAttribute : Attribute
{
    private readonly int order_;
    public OrderAttribute([CallerLineNumber]int order = 0)
    {
        order_ = order;
    }

    public int Order { get { return order_; } }
}

public class MyClass
{
    [Order] public string string1 { get; set; }
    [Order] public string string2 { get; set; }
    [Order] public string string3 { get; set; }
    [Order] public string string4 { get; set; }   
}

With the Attributes, I can get the sequence using:

var properties = from property in typeof(MyClass).GetProperties()
                         where Attribute.IsDefined(property, typeof(OrderAttribute))
                         orderby ((OrderAttribute)property
                                   .GetCustomAttributes(typeof(OrderAttribute), false)
                                   .Single()).Order
                         select property;

What I'm looking also, is to have the possibility to get an integer that acts as the index of the property in the class. Example:

    string stringData = string.Format("A{0}B{0}C{0}D", "\t");  //usually my data comes in multiple strings like this
    var dataSplit = stringData.Split('\t');
    string var1 = dataSplit[0];
    string var4 = dataSplit[3];

Where 0 and 3 give me the sequence I need from the split[n]. But, if I would like to have something like a GetIndex method, that would be extremely helpful:

    MyClass myClass = new MyClass();
    string var1_alt = dataSplit[GetIndex(myClass.string1)];
    string var4_alt = dataSplit[GetIndex(myClass.string4)];

Use the property of that class to return the integer that represents its position in the class (similar to an enum). I would like to use myClass.string1 as the class property to get the index and not as the string value it holds when filed.

I'll appreciate any help.





Aucun commentaire:

Enregistrer un commentaire