处理反射中的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;
}

这如何实现?以上方法都不适合我。

jakela 回答:处理反射中的null

这是一个示例,显示了如何处理从属性返回的空值。

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

大家都在问