首页 > 解决方案 > 如何从类/对象 C# 中检索所有属性

问题描述

假设我有这个课程:

public class Test
{
    public string Attribute1 { get; set; }
    public int Attribute2 { get; set; }
}

我有这个类的对象

Test test = new Test();

现在我想填充这个对象,但是我不知道里面有什么属性。如何获取属性的引用来填充它们?我在想这样的事情:

        List<object> attrs = GetAttributes<Test>(test);
        foreach (var attr in attrs)
        {
            if(attr.GetType() == typeof(string))
            {
                attr = "filled";
            }
            else
            {
                attr = 1;
            }
        }
        Console.WriteLine(test.Attribute1); //print "filled"
        Console.WriteLine(test.Attribute2); //print 1

标签: c#.nettypesreference

解决方案


推荐阅读