In C# is there a way retrieve only built-in data t

2019-02-18 11:19发布

Using reflection I'd like to retrieve only the built-in data type properties from a C# object. Is there a better way to do that then using a bunch of || (ors) in a Where method specifying the types I am interested in?

Type sourceType = typeof(TSource);

var props = sourceType.GetProperties()
    .Where(pi => pi.PropertyType == typeof(int)
              || pi.PropertyType == typeof(string));    // .... etc.

2条回答
太酷不给撩
2楼-- · 2019-02-18 12:02

They are all in the System namespace, so you could at least filter to namespace, other than that, at least the list isn't too long. You wouldn't chain Where's either, you'd use ||'s, that code won't work.

查看更多
来,给爷笑一个
3楼-- · 2019-02-18 12:16

Are you looking for integral types to the BCL? Or value types only? (IE integer, char, etc)

If so, you could test for pi.PropertyType.IsPrimitive() and then test for string type as part of the or clause...

var props = sourceType.GetProperties()
    .Where(pi => .PropertyType.IsPrimitive
              || pi.PropertyType == typeof(string))
查看更多
登录 后发表回答