我在类中有一个类我有一些属性如何获取属性数据类型,属性值及其属性名称

我在类中有一个类我有一些属性如何获取属性数据类型,属性值及其属性名称

问题描述:

我在类中有一个类我有一些属性如何获取属性数据类型,属性值及其属性名称

例如



公共类人员

{

[必填]

public int ID {get; set;}

}



我尝试了什么:



公共类人
{

[必填]

public int ID {get; set;}

}

i have a class inside the class i have some properties how i get properties data type ,properties values and its attribute Name
for example

public class Person
{
[Required]
public int ID{get;set;}
}

What I have tried:

public class Person
{
[Required]
public int ID{get;set;}
}

试试这个



try this

class Program
{
    static void Main(string[] args)
    {
        Person obj = new Person();
        obj.ID = 34;
       var props = typeof(Person).GetProperties().ToList();
       foreach (var item in props)
       {
           string propertyName = item.Name; // ID
           string type = item.PropertyType.Name; // Int32
           object value = item.GetValue(obj,null); // 34
           var attribute = item.GetCustomAttributes(true)[0]; // Required
            
       }

    } 
}

public class Person
{
    [Required]
    public int ID { get; set; }
}

public class Required : Attribute
{
 
}


如果您看一下:将列表转换为数据表 [ ^ ]它将 List< T> 转换为一个 DataTable 通过查看类属性 - 它给出了每个属性的名称和类型。

每个属性也有属性集合,此提示使用来自集合中多行的图表 [ ^ ]使用决定是否应该绘制一个属性。



它们一起为您提供所需的代码。
If you have a look at this: Converting a List to a DataTable[^] it converts a List<T> to a DataTable by looking at the class properties - which gives you the name and Type of each property.
Each property also has an Attributes collection, which this tip Using a Chart With Multiple Lines From A Collection[^] uses to decide if a property should be charted or not.

Together, they give you the code you need.