c#

怎么获取C#类的属性

小亿
141
2023-08-07 14:47:59
栏目: 编程语言

要获取C#类的属性,可以使用反射来实现。反射是一种在运行时获取类的信息的机制。以下是一个示例代码,演示如何使用反射获取类的属性:

using System;
using System.Reflection;
public class MyClass
{
public int MyProperty { get; set; }
}
public class Program
{
public static void Main()
{
Type type = typeof(MyClass);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.Name);
}
}
}

在上面的示例中,我们定义了一个名为MyClass的类,并在其中定义了一个属性MyProperty。然后,我们使用typeof操作符获取MyClass类的Type对象。接下来,我们使用Type对象的GetProperties方法获取所有属性的PropertyInfo对象数组。最后,我们遍历PropertyInfo数组,并打印出每个属性的名称。

输出结果将是:

MyProperty

这样,我们就成功获取了MyClass类的属性。

0
看了该问题的人还看了