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

在C#中有类似Python的getattr()吗?

在C#中,没有与Python的getattr()完全相同的功能。但是,您可以使用反射来实现类似的效果。以下是一个示例:

代码语言:csharp
复制
using System;

public class Example
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }

    public static void Main()
    {
        Example example = new Example();
        example.Property1 = "Hello, World!";
        example.Property2 = 42;

        string propertyName = "Property1";
        object value = GetPropertyValue(example, propertyName);
        Console.WriteLine($"The value of {propertyName} is: {value}");

        propertyName = "Property2";
        value = GetPropertyValue(example, propertyName);
        Console.WriteLine($"The value of {propertyName} is: {value}");
    }

    public static object GetPropertyValue(object obj, string propertyName)
    {
        Type type = obj.GetType();
        System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
        if (propertyInfo == null)
        {
            throw new ArgumentException($"The property {propertyName} does not exist on {type.Name}");
        }

        return propertyInfo.GetValue(obj);
    }
}

在这个示例中,我们定义了一个名为Example的类,该类具有两个属性:Property1(字符串类型)和Property2(整数类型)。我们还定义了一个名为GetPropertyValue的方法,该方法接受一个对象和一个属性名称,并使用反射来获取该属性的值。

Main方法中,我们创建了一个Example对象,并设置了它的属性值。然后,我们使用GetPropertyValue方法来获取这些属性的值,并将它们打印到控制台上。

请注意,这个示例仅适用于公共属性。如果您需要访问私有属性,您需要修改GetPropertyValue方法以使用BindingFlags参数,以便在需要时允许非公共属性的访问。

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

相关·内容

领券