以顺序顺序遍历类的所有属性(类声明)

时间:2018-12-11 22:08:42

标签: c# reflection

我需要获取先前已用数据填充的类元素/项目的所有属性的所有值。 类示例:

public class MyClass
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
    public string prop4 { get; set; }
}

在我的代码中的某处:

MyClass myClass = new MyClass();
List<MyClass> myList = new List<MyClass>();

MyClass myElement = new MyClass()
{
    prop1 = "A",
    prop2 = "B",
    prop3 = "C",
    prop4 = "D",
};
myList.Add(myElement);

string wholeString_opt1 = 
    myElement.prop1 + "\t" + 
    myElement.prop2 + "\t" +
    myElement.prop3 + "\t" + 
    myElement.prop4 + "\t";

在我的情况下,我添加所有属性值的顺序是基本的(从第一个属性到最后一个属性,它必须具有该顺序)。 该示例显示了一个简单的唯一元素列表。 我的课程的属性非常相似(均以prop开头),但在许多情况下,课程中的名称不是按字母顺序排列的。 这意味着,如果我的类中有大量具有不同起始字符的属性,则对属性进行排序时'wholeString_opt1'的结果将是正确的,但它非常费力。

另一种选择是:

PropertyInfo[] myClassProperties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in myClassProperties)
{
    wholeString_opt2 += property.GetValue(myElement).ToString() + "\t";
}

“ wholeString_opt2”的结果相同,但前提是该类的属性如上所示。 如果有,例如:

MyClass myElement = new MyClass()
{
    prop1 = "A",
    prop2 = "B",
    anotherProp3 = "C",
    prop4 = "D",
};

.GetProperties()的排序将丢失。

有什么办法可以解决这个问题? 我可能有超过25个属性的案例... 也许还有其他选择?

1 个答案:

答案 0 :(得分:1)

我认为您可以按照TheGeneral的建议在此处使用属性。

例如,给定以下PostionAttribute:

    [AttributeUsage(AttributeTargets.Property)]
    public sealed class PositionAttribute : Attribute
    {
        public PositionAttribute(int position)
        {
            Position = position;
        }

        public int Position { get; private set; }
    }

我们可以根据需要指定MyClass中每个属性的顺序,例如:

public class MyClass
    {
        [Position(1)]
        public string prop1 { get; set; }

        [Position(2)]
        public string prop2 { get; set; }

        [Position(3)]
        public string anotherProp3 { get; set; }            

        [Position(4)]
        public string prop4 { get; set; }
    }

要测试上述更改,请尝试:

        var myClass = new MyClass();
        var myList = new List<MyClass>();

        var myElement = new MyClass()
         {
              prop1 = "A",
              prop2 = "B",
              anotherProp3 = "C",
              prop4 = "D",
         };

       var values = typeof(MyClass).GetProperties()
                    .OrderBy(p => Attribute.IsDefined(p, typeof(PositionAttribute)) ? p.GetCustomAttribute<PositionAttribute>().Position : int.MaxValue)
                    .Select(p => p.GetValue(myElement))
                    .ToArray();

       var result = string.Join("\t", values);

输出将为"A B C D"

可以从here中找到另一个好的解决方案。

希望有帮助。

相关问题