gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:43:02 25 4
gpt4 key购买 nike

我试图找出一个变量是否是一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com