首页 > 解决方案 > 在反射中处理 null

问题描述

如何处理返回带有计数的属性值的非静态方法的空值,即当我们有propertyName并且没有为此属性设置值时

public object Property(propertyName)
{
    return car.GetType().GetProperty(propertyName).GetValue(car, null);
}

我尝试过的不同方法:

第一种方法:

public object Property(propertyName)
{
    return (car.GetType().GetProperty(propertyName).GetValue(car, null)).Value;
}

这对我不起作用。

第二种方法:

public object Property(propertyName)
{
    var value = car.GetType().GetProperty(propertyName).GetValue(car, null);
    if (value != null)
        return  value;
    else
        return value;
}

如何做到这一点?以上方法都不适合我。

标签: c#system.reflection

解决方案


下面的示例展示了如何处理从属性返回的空值。

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);
        }
    }
}

推荐阅读