c# - 在反射中处理 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;
}
如何做到这一点?以上方法都不适合我。
解决方案
下面的示例展示了如何处理从属性返回的空值。
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);
}
}
}
推荐阅读
- javascript - 画布上的相机
- go - 去测试从 VS 代码到终端的不可重现的输出
- java - Spring Data JPA Query方法重复对象
- spring-boot - 使用千分尺时的 Prometheus 端点错误
- asp.net - 页面生成以适应列表溢出
- android - Android位置:绝对不应该在有边框的容器内被切断
- azure-active-directory - 通过应用注册门户创建的应用在 Azure Active Directory->应用注册列表中不可见
- angular - Angular 2 ngOnchange 事件被调用,与任何更改无关
- python - 如何将函数输出用作另一个函数的输入
- sbt - 如何指定包含空格的任务键名称?