我如何获得一个类的所有属性的列表?
当前回答
你可以使用反射来做到这一点: (从我的库中获取名称和值)
public static Dictionary<string, object> DictionaryFromType(object atype)
{
if (atype == null) return new Dictionary<string, object>();
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (PropertyInfo prp in props)
{
object value = prp.GetValue(atype, new object[]{});
dict.Add(prp.Name, value);
}
return dict;
}
这个东西对带索引的属性不起作用——因为(它变得笨拙了):
public static Dictionary<string, object> DictionaryFromType(object atype,
Dictionary<string, object[]> indexers)
{
/* replace GetValue() call above with: */
object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}
同样,只获取公共属性:(参见MSDN on BindingFlags enum)
/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
这也适用于匿名类型! 只需要知道名字:
public static string[] PropertiesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
List<string> propNames = new List<string>();
foreach (PropertyInfo prp in props)
{
propNames.Add(prp.Name);
}
return propNames.ToArray();
}
对于值来说是一样的,或者你可以使用:
GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
但我想这有点慢。
其他回答
这是改进后的@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();
}
根据@MarcGravell的回答,这里有一个在Unity c#中工作的版本。
ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}
下面的代码将提供类属性/属性/表列的列表
var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();
我也面临着这样的要求。
从这次讨论中,我有了另一个想法,
Obj.GetType().GetProperties()[0].Name
这也显示了属性名。
Obj.GetType().GetProperties().Count();
这显示了属性的数量。
谢谢大家。这是一个很好的讨论。
你可以使用这个系统。使用Type.GetProperties()方法的反射命名空间:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
推荐文章
- 如何强制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请求头