我如何获得一个类的所有属性的列表?
当前回答
下面的代码将提供类属性/属性/表列的列表
var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();
其他回答
你可以使用这个系统。使用Type.GetProperties()方法的反射命名空间:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
反射;例如:
obj.GetType().GetProperties();
对于一种类型:
typeof(Foo).GetProperties();
例如:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
以下反馈…
要获取静态属性的值,将null作为GetValue的第一个参数 要查看非公共属性,请使用(例如)GetProperties(BindingFlags)。Public | BindingFlags。NonPublic | BindingFlags.Instance)(返回所有公共/私有实例属性)。
你可以使用反射来做到这一点: (从我的库中获取名称和值)
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
但我想这有点慢。
我也面临着这样的要求。
从这次讨论中,我有了另一个想法,
Obj.GetType().GetProperties()[0].Name
这也显示了属性名。
Obj.GetType().GetProperties().Count();
这显示了属性的数量。
谢谢大家。这是一个很好的讨论。
下面的代码将提供类属性/属性/表列的列表
var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务