要从C# 2.0中的属性获取属性的名称,您可以使用反射API。以下是一个示例代码:
using System;
using System.Reflection;
public class MyClass
{
public string MyProperty { get; set; }
}
public class Program
{
public static void Main()
{
Type myClassType = typeof(MyClass);
PropertyInfo[] properties = myClassType.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Property Name: " + property.Name);
}
}
}
在这个示例中,我们首先使用typeof
关键字获取MyClass
类型的Type
对象。然后,我们使用GetProperties()
方法获取类型的所有属性。最后,我们遍历属性并输出它们的名称。
这个示例将输出:
Property Name: MyProperty
这个方法适用于C# 2.0及更高版本。
领取专属 10元无门槛券
手把手带您无忧上云