首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用C#中的变量调用对象的属性,例如customer.&fieldName

在C#中,可以使用反射来实现使用变量名来调用对象的属性。以下是一个示例代码:

代码语言:csharp
复制
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的类,该类具有NameAge属性。我们创建了一个Customer对象,并创建了一个字符串变量fieldName,该变量的值为"Name"

接下来,我们使用GetType()方法获取Customer对象的类型,并使用GetProperty()方法获取fieldName对应的属性信息。然后,我们使用GetValue()方法获取该属性的值,并将其输出到控制台。

这种方法可以用于任何对象和属性,只需将CustomerfieldName替换为您自己的类和属性名称即可。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券