返回类的所有属性,不为 null c#

Jam*_*mes 2 c# class

我一直在寻找并发现这描述了如果值为 null 则返回 bool。我使用的代码来自此片段 Client client = new Client{ FirstName = "James"};

client.GetType().GetProperties()
.Where(pi => pi.GetValue(client) is string)
.Select(pi => (string) pi.GetValue(client))
.Any(value => string.IsNullOrEmpty(value));
Run Code Online (Sandbox Code Playgroud)

但我不想返回值是否为空(bool)的情况,而是想检索所有不为空的属性值。

我尝试更改代码,但没有成功。

非常感谢

编辑

public class Client
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   //...
}

Client client = new Client();
client.FirstName = "James";
client.LastName = "";
Run Code Online (Sandbox Code Playgroud)

使用我的“Client”类,我想迭代类中的所有属性,并且当值不为 null 或空字符串时,我将返回该值,在本例中,我只会返回一个字符串“James ”。

希望这是有道理的。

Ste*_*ris 5

有一些问题:

return myObject.GetType().GetProperties()
.Where(pi => pi.GetValue(myObject) is string) // this wastes time getting the value
.Select(pi => (string) pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value)); //  Any will return a bool
Run Code Online (Sandbox Code Playgroud)

所以将其更改为:

return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string)) // check type
.Select(pi => (string)pi.GetValue(myObject)) // get the values
.Where(value => !string.IsNullOrEmpty(value)); // filter the result (note the !)
Run Code Online (Sandbox Code Playgroud)

另外,请确保您的属性是属性而不是字段。