我如何获得一个类的所有属性的列表?
当前回答
你可以使用这个系统。使用Type.GetProperties()方法的反射命名空间:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
其他回答
根据@MarcGravell的回答,这里有一个在Unity c#中工作的版本。
ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}
我也面临着这样的要求。
从这次讨论中,我有了另一个想法,
Obj.GetType().GetProperties()[0].Name
这也显示了属性名。
Obj.GetType().GetProperties().Count();
这显示了属性的数量。
谢谢大家。这是一个很好的讨论。
这是改进后的@lucasjones的回答。在他的回答之后,我在评论部分提到了一些改进。我希望有人会觉得这有用。
public static string[] GetTypePropertyNames(object classObject, BindingFlags bindingFlags)
{
if (classObject == null)
{
throw new ArgumentNullException(nameof(classObject));
}
var type = classObject.GetType();
var propertyInfos = type.GetProperties(bindingFlags);
return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
}
你可以使用这个系统。使用Type.GetProperties()方法的反射命名空间:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
下面的代码将提供类属性/属性/表列的列表
var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();
推荐文章
- 如何强制LINQ Sum()返回0而源集合是空的
- 将值附加到查询字符串
- Selenium c# WebDriver:等待元素出现
- 我如何添加双引号的字符串,是在一个变量?
- 如何创建数组。包含不区分大小写的字符串数组?
- 检查字符串是否包含字符串列表中的元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头