c# - 正确区分bool?和 bool 在 C#

标签 c# reflection

我试图找出一个变量是否是一个简单的 boolNullable<bool> .

好像是

if(val is Nullable<bool>)

bool 均返回真和 Nullable<bool>变量和

if(val is bool)

对于 bool 也都返回 true和 Nullable<bool> .

基本上,我感兴趣的是找出一个简单的 bool变量为 true OR 如果 Nullable<bool>变量不为空

有什么方法可以做到这一点?

完整代码如下:

List<string> values = typeof(InstViewModel).GetProperties()
                          .Where(prop => prop != "SubCollection" && prop != "ID" && prop != "Name" && prop != "Level")
                          .Select(prop => prop.GetValue(ivm, null))
                          .Where(val => val != null && (val.GetType() != typeof(bool) || (bool)val == true))      //here I'm trying to check if val is bool and true or if bool? and not null
                          .Select(val => val.ToString())
                          .Where(str => str.Length > 0)
                          .ToList();

InstViewModel对象:

 public class InstViewModel
    {
        public string SubCollection { get; set; }
        public string ID { get; set; }
        public string Name { get; set; }
        public string Level { get; set; }
        public bool Uk { get; set; }
        public bool Eu { get; set; }
        public bool Os { get; set; }
        public Nullable<bool> Mobiles { get; set; }
        public Nullable<bool> Landlines { get; set; }
        public Nullable<bool> UkNrs { get; set; }
        public Nullable<bool> IntNrs { get; set; }
}

这里我的代码的重点是找出是否所有对象的值都是 null (更具体地说,找出任何不为 null 的值并将它们保存在 List<string> 中)。然而,当试图区分 bool 时,这会使 lambda 表达式变得复杂。和 bool?输入我的对象(第二个 Where 语句)。

此外,由于该对象也包含一些字符串类型,我试图在我的第一个 .Where 中排除这些类型声明(我目前可能做得不对,因为它似乎不起作用)。但我的主要目标是区分 boolbool?类型。

最佳答案

有一种简单的方法可以检查变量是声明为 T 还是 T?:

private static bool IsNullable<T>(T val)
{
    return false;
}

private static bool IsNullable<T>(T? val)
    where T : struct
{
    return true;
}

用法:

bool? val = false;

if (IsNullable(val))
{
    ...
}

编辑
为已编辑的问题尝试以下代码:

var boolProps = typeof (InstViewModel).GetProperties()
    .Where(prop => prop.PropertyType == typeof(bool))
    .Select(prop => (bool)prop.GetValue(ivm, null))
    .Select(v => v ? v.ToString() : String.Empty);

var nullableBoolProps = typeof(InstViewModel).GetProperties()
    .Where(prop => prop.PropertyType == typeof(bool?))
    .Select(prop => (bool?)prop.GetValue(ivm, null))
    .Select(v => v.HasValue ? v.ToString() : String.Empty);

List<string> values = boolProps.Concat(nullableBoolProps)
              .Where(str => str.Length != 0)
              .ToList();

关于c# - 正确区分bool?和 bool 在 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641354/

相关文章:

c# - 在发送消息中收到所有数据之前,TCPStream.Read 会阻塞吗?

c# - 如何修复 webAPI 中不正确的操作路由

c# - MethodInfo.MetadataToken 的目的是什么

Java Reflection - 如何为从 One 和 Two 扩展的类设置值

wpf - 什么可以阻止 MEF 或 Prism 加载我的类型?

c# - 将 Assembly 保存为适合 Assembly.Load 的字节数组

c# - 尝试将值与字符串进行比较时 C# 出错

c# - Stacktraces 在实时网站上危险吗?

javascript - Mvc完成异步脚本加载

pointers - 确认 Go 中的结构字段非零