租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

如何获取C#类的属性,c#获取所有子类

发布时间:2023-08-08 07:56:02

如何获得C#类的属性

要获得C#类的属性,可使用反射来实现。反射是一种在运行时获得类的信息的机制。以下是一个示例代码,演示怎样使用反射获得类的属性:
```csharp
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`类的属性。