简体   繁体   English

如何获得物业名称

[英]How to get a property's name

is there a way to get the name of a property of an object? 有没有一种方法来获取对象的属性名称?

For example if I have: 例如,如果我有:

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

and

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

How can I get the name of the Make property in the code? 如何在代码中获取Make属性的名称?

ie. 即。 that car.Make has the name "Make". car.Make的名字叫"Make". So I want to get the string "Make" 所以我想得到字符串"Make"

I'm wanting to do this because I'm wanting to pass the property name to a method. 我想要这样做是因为我想将属性名称传递给方法。

Update: 更新:

I want the name of the property not an array of properties: 我希望属性名称不是属性数组:

Found the answer here: 在这里找到答案:

http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/ http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/

typeof(Car).GetProperties();

然后遍历列表

  Type typ = car.GetType();
  PropertyInfo[] pi = typ.GetProperties();

would fetch all properties 将获取所有属性

You can then do a .Name for pi elements 然后可以为pi元素做一个.Name

I want the name of the property not an array of properties: 我希望属性名称不是属性数组:

Found the answer here: 在这里找到答案:

http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/ http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM