Обрабатывать нуль в отражении - PullRequest
0 голосов
/ 16 марта 2020

Как обрабатывать нулевое значение для метода non-stati c, который возвращает значение свойства с count, т.е. когда у нас есть 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;
}

Как этого достичь ? Ни один из вышеперечисленных подходов не помог мне.

Ответы [ 2 ]

1 голос
/ 16 марта 2020

Вот пример, который показывает, как обрабатывать нулевое значение, возвращаемое из свойства.

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);
        }
    }
}
0 голосов
/ 17 марта 2020

return car.GetType (). GetProperty (propertyName) ?. GetValue (car, null); }

Это разрешает нулевое значение propertyName, если его свойство не установлено, тогда мы можем использовать условие Null.

...