在C#中,有一种方法可以使用反射检索内置数据类型属性

ahs*_*ele 4 c# reflection lambda

使用反射我只想从C#对象中检索内置数据类型属性.有没有更好的方法,然后||Where指定我感兴趣的类型的方法中使用一堆(ors)?

Type sourceType = typeof(TSource);

var props = sourceType.GetProperties()
    .Where(pi => pi.PropertyType == typeof(int)
              || pi.PropertyType == typeof(string));    // .... etc.
Run Code Online (Sandbox Code Playgroud)

Ric*_*ein 6

它们都在System命名空间中,因此您至少可以过滤到命名空间,除此之外,至少列表不会太长.你不会链接Where's,你使用||的,代码将不起作用.


Kil*_*ash 5

你在寻找BCL的整体类型吗?或仅限值类型?(IE整数,字符等)

如果是这样,你可以测试pi.PropertyType.IsPrimitive()然后测试字符串类型作为or子句的一部分...

var props = sourceType.GetProperties()
    .Where(pi => .PropertyType.IsPrimitive
              || pi.PropertyType == typeof(string))
Run Code Online (Sandbox Code Playgroud)