相关疑难解决方法(0)

通过反射查找可空属性的类型

我通过反射检查对象的属性,并继续处理每个属性的数据类型.这是我的(减少的)来源:

private void ExamineObject(object o)
{
  Type type = default(Type);
  Type propertyType = default(Type);
  PropertyInfo[] propertyInfo = null;

  type = o.GetType();

  propertyInfo = type.GetProperties(BindingFlags.GetProperty |
                                    BindingFlags.Public |
                                    BindingFlags.NonPublic |
                                    BindingFlags.Instance);
  // Loop over all properties
  for (int propertyInfoIndex = 0; propertyInfoIndex <= propertyInfo.Length - 1; propertyInfoIndex++)
  {
    propertyType = propertyInfo[propertyInfoIndex].PropertyType;
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我新近需要处理可空属性,但我不知道如何获得可空属性的类型.

.net c# reflection nullable

76
推荐指数
4
解决办法
4万
查看次数

可空类型不是可以为空的类型?

我正在使用可空类型进行一些测试,并且它没有像我预期的那样工作:

int? testInt = 0;
Type nullableType = typeof(int?);
Assert.AreEqual(nullableType, testInt.GetType()); // not the same type
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable)); //FAIL 

DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable<>)); //STILL FAIL
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么testInt.GetType()返回int,而typeof(int?)返回真正的可空类型?

.net c# nullable gettype

44
推荐指数
2
解决办法
4423
查看次数

为什么GetType返回System.Int32而不是Nullable <Int32>?

为什么这个代码段的输出System.Int32代替Nullable<Int32>

int? x = 5;
Console.WriteLine(x.GetType());
Run Code Online (Sandbox Code Playgroud)

.net c# reflection nullable gettype

29
推荐指数
2
解决办法
6757
查看次数

标签 统计

.net ×3

c# ×3

nullable ×3

gettype ×2

reflection ×2