gpt4 book ai didi

c# - 如何根据名称获取属性值

转载 作者:IT王子 更新时间:2023-10-29 03:32:52 26 4
gpt4 key购买 nike

有没有办法根据对象的名称获取对象的属性值?

例如,如果我有:

public class Car : Vehicle
{
public string Make { get; set; }
}

var car = new Car { Make="Ford" };

我想写一个方法,我可以在其中传递属性名称,它会返回属性值。即:

public string GetPropertyValue(string propertyName)
{
return the value of the property;
}

最佳答案

return car.GetType().GetProperty(propertyName).GetValue(car, null);

关于c# - 如何根据名称获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5508050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com