这是一个示例,显示了如何处理从属性返回的空值。
public class Car
{
public string Name { get { return "Honda"; } }
public string SomethingNull { get { return null; } }
}
public class Foo
{
object car = new Car();
public object Property(string propertyName)
{
System.Reflection.PropertyInfo property = car.GetType().GetProperty(propertyName);
if (property == null) {
throw new Exception(string.Format("Property {0} doesn't exist",propertyName));
}
return property.GetValue(car,null);
}
}
class Program
{
public static void Demo(Foo foo,string propertyName)
{
object propertyValue = foo.Property(propertyName);
if (propertyValue == null)
{
Console.WriteLine("The property {0} value is null",propertyName);
}
else
{
Console.WriteLine("The property {0} value is not null and its value is {1}",propertyName,propertyValue);
}
}
static void Main(string[] args)
{
Foo foo = new Foo();
Demo(foo,"Name");
Demo(foo,"SomethingNull");
try
{
Demo(foo,"ThisDoesNotExist");
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
}
}
,
返回car.GetType()。GetProperty(propertyName)?. GetValue(car,null);
}
如果没有设置propertyName,则允许null值为null,那么我们可以使用Null条件。
本文链接:https://www.f2er.com/2636813.html