J'attire spécifiquement l'attention sur la propagation de zéro en ce qui concerne bool?
et l'utilisation d'une méthode de retour bool
. Par exemple, considérer les points suivants:Pourquoi la propagation de type NULL se produit de manière incohérente Nullable <T>?
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
}
Cela ne compile pas, et l'erreur suivante existe:
ne peut pas convertir implicitement bool? booler. Une conversion explicite existe (manque-t-il une distribution)?
Cela implique qu'il traite le corps entier de la méthode comme bool?
, en tant que tel, je suppose que je pourrais dire .GetValueOrDefault()
après la .Any()
mais ce n'est pas autorisé comme .Any()
retours bool
pas bool?
.
Je sais que je pouvais faire une des opérations suivantes comme une œuvre autour de:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
Ou
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
var any =
property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
return any.GetValueOrDefault();
}
Ou
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
Ma question est, pourquoi je ne peux pas invoquer directement .GetValueOrDefault()
enchaînement sur l'invocation .Any()
?
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return (property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any())
.GetValueOrDefault();
}
Je pense que ce serait logique que la valeur est en fait bool?
à ce stade et non bool
.
Vous devriez mettre entre parenthèses, donc 'opérateur .' connu, où la chaîne d'appel état termine: '(propriété? .AttributeProvider.GetAttributes (typeof (TAttribute), false) .Any()). GetValueOrDefault()'. – PetSerAl
Si 'propriété' est null, la méthode tentera de retourner null. Cependant, il ne peut pas parce que le type de retour est 'bool', qui n'est pas un type nullable. Changez le type de retour en 'bool?'. – Abion47