C# 对象中查找某一个属性
在C#中,可以使用反射来查找对象中的属性。以下是一个示例代码:
using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var person = new Person { Name = "John", Age = 25 };
PropertyInfo propertyInfo = person.GetType().GetProperty("Name");
if (propertyInfo != null)
{
var value = propertyInfo.GetValue(person);
Console.WriteLine($"Name: {value}");
}
}
}
在上述代码中,我们创建了一个Person类,有Name和Age两个属性。然后我们创建了一个Person对象,通过反射获取了Name属性,并输出其值。
运行结果:
Name: John
如果要查找的属性存在,GetProperty方法将返回一个PropertyInfo对象,可以通过它来获取属性值。如果要查找的属性不存在,GetProperty方法将返回null。
请注意,使用反射可能会影响性能,因此应该谨慎使用。如果只需要在代码中访问对象的属性,最好直接使用对象.属性的方式来访问。
原文地址: https://www.cveoy.top/t/topic/i514 著作权归作者所有。请勿转载和采集!