在C#中,可以使用反射来实现使用变量名来调用对象的属性。以下是一个示例代码:
using System;
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
Customer customer = new Customer { Name = "John", Age = 30 };
string fieldName = "Name";
Type customerType = customer.GetType();
PropertyInfo propertyInfo = customerType.GetProperty(fieldName);
object value = propertyInfo.GetValue(customer, null);
Console.WriteLine($"The value of {fieldName} is {value}");
}
}
在这个示例中,我们创建了一个名为Customer
的类,该类具有Name
和Age
属性。我们创建了一个Customer
对象,并创建了一个字符串变量fieldName
,该变量的值为"Name"
。
接下来,我们使用GetType()
方法获取Customer
对象的类型,并使用GetProperty()
方法获取fieldName
对应的属性信息。然后,我们使用GetValue()
方法获取该属性的值,并将其输出到控制台。
这种方法可以用于任何对象和属性,只需将Customer
和fieldName
替换为您自己的类和属性名称即可。
腾讯云存储知识小课堂
腾讯云存储专题直播
T-Day
开箱吧腾讯云
企业创新在线学堂
云+社区技术沙龙[第14期]
腾讯位置服务技术沙龙
Elastic 中国开发者大会
Techo Day
云+社区技术沙龙第33期
腾讯云GAME-TECH游戏开发者技术沙龙
领取专属 10元无门槛券
手把手带您无忧上云