在C#中,没有与Python的getattr()完全相同的功能。但是,您可以使用反射来实现类似的效果。以下是一个示例:
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
参数,以便在需要时允许非公共属性的访问。
领取专属 10元无门槛券
手把手带您无忧上云