CA1304 : Spécifier CultureInfoCA1304: Specify CultureInfo
TypeNameTypeName | SpecifyCultureInfoSpecifyCultureInfo |
CheckIdCheckId | CA1304CA1304 |
CategoryCategory | Microsoft.GlobalizationMicrosoft.Globalization |
Modification avec ruptureBreaking Change | Sans ruptureNon-breaking |
CauseCause
Une méthode ou un constructeur appelle un membre présentant une surcharge qui accepte un System.Globalization.CultureInfo paramètre et la méthode ou le constructeur n’appelle pas la surcharge qui accepte le CultureInfo paramètre.A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. Cette règle ignore les appels aux méthodes suivantes :This rule ignores calls to the following methods:
Description de la règleRule Description
Lorsqu’un CultureInfo ou System.IFormatProvider objet n’est pas fourni, la valeur par défaut fournie par le membre surchargé n’est peut-être pas l’effet que vous souhaitez dans tous les paramètres régionaux.When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. En outre, .NET Framework.NET Framework membres choisissent la culture par défaut et la mise en forme en fonction d’hypothèses qui peuvent ne pas être correctes pour votre code.Also, .NET Framework.NET Framework members choose default culture and formatting based on assumptions that might not be correct for your code. Pour garantir que le code fonctionne comme prévu pour vos scénarios, vous devez fournir des informations spécifiques à la culture selon les consignes suivantes :To ensure the code works as expected for your scenarios, you should supply culture-specific information according to the following guidelines:
Si la valeur doit être affichée à l’utilisateur, utilisez la culture actuelle.If the value will be displayed to the user, use the current culture. Consultez System.Globalization.CultureInfo.CurrentCulture.See System.Globalization.CultureInfo.CurrentCulture.
Si la valeur est stockée et accessibles par logiciel, c'est-à-dire rendue persistante dans un fichier ou d’une base de données, utilisez la culture dite indifférente.If the value will be stored and accessed by software, that is, persisted to a file or database, use the invariant culture. Consultez System.Globalization.CultureInfo.InvariantCulture.See System.Globalization.CultureInfo.InvariantCulture.
Si vous ne connaissez pas la destination de la valeur, ont le consommateur de données ou le fournisseur de spécifier la culture.If you do not know the destination of the value, have the data consumer or provider specify the culture.
Notez que System.Globalization.CultureInfo.CurrentUICulture est utilisé uniquement pour récupérer des ressources localisées à l’aide d’une instance de la System.Resources.ResourceManager classe.Note that System.Globalization.CultureInfo.CurrentUICulture is used only to retrieve localized resources by using an instance of the System.Resources.ResourceManager class.
Même si le comportement par défaut du membre surchargé est adapté à vos besoins, il est préférable d’appeler explicitement la surcharge spécifique à la culture afin que votre code soit documentés et plus facile à maintenir.Even if the default behavior of the overloaded member is appropriate for your needs, it is better to explicitly call the culture-specific overload so that your code is self-documenting and more easily maintained.
Comment corriger les violationsHow to Fix Violations
Pour corriger une violation de cette règle, utilisez la surcharge qui accepte un CultureInfo ou IFormatProvider et spécifiez l’argument selon les règles qui ont été citées plus haut.To fix a violation of this rule, use the overload that takes a CultureInfo or IFormatProvider and specify the argument according to the guidelines that were listed earlier.
Quand supprimer les avertissementsWhen to Suppress Warnings
Il est possible de supprimer un avertissement de cette règle lorsque vous êtes certain que le fournisseur de format/culture par défaut est le bon choix, et où la maintenabilité du code n’est pas une priorité de développement importants.It is safe to suppress a warning from this rule when it is certain that the default culture/format provider is the correct choice, and where code maintainability is not an important development priority.
ExempleExample
Dans l’exemple suivant, BadMethod
provoque deux violations de cette règle.In the following example, BadMethod
causes two violations of this rule. GoodMethod
corrige la première violation en passant la culture dite indifférente à System.String.Compare et corrige la deuxième violation en passant la culture actuelle à ToLower car string3
est affiché à l’utilisateur.GoodMethod
corrects the first violation by passing the invariant culture to System.String.Compare, and corrects the second violation by passing the current culture to ToLower because string3
is displayed to the user.
using System;
using System.Globalization;
namespace GlobalizationLibrary
{
public class CultureInfoTest
{
public void BadMethod(String string1, String string2, String string3)
{
if(string.Compare(string1, string2, false) == 0)
{
Console.WriteLine(string3.ToLower());
}
}
public void GoodMethod(String string1, String string2, String string3)
{
if(string.Compare(string1, string2, false,
CultureInfo.InvariantCulture) == 0)
{
Console.WriteLine(string3.ToLower(CultureInfo.CurrentCulture));
}
}
}
}
ExempleExample
L’exemple suivant montre l’effet de la culture en cours sur la valeur par défaut IFormatProvider qui est sélectionné par le DateTime type.The following example shows the effect of current culture on the default IFormatProvider that is selected by the DateTime type.
using System;
using System.Globalization;
using System.Threading;
namespace GlobalLibGlobalLibrary
{
public class IFormatProviderTest
{
public static void Main()
{
string dt = "6/4/1900 12:15:12";
// The default behavior of DateTime.Parse is to use
// the current culture.
// Violates rule: SpecifyIFormatProvider.
DateTime myDateTime = DateTime.Parse(dt);
Console.WriteLine(myDateTime);
// Change the current culture to the French culture,
// and parsing the same string yields a different value.
Thread.CurrentThread.CurrentCulture = new CultureInfo("Fr-fr", true);
myDateTime = DateTime.Parse(dt);
Console.WriteLine(myDateTime);
}
}
}
Cet exemple produit la sortie suivante.This example produces the following output.
6/4/1900 12:15:12 PM6/4/1900 12:15:12 PM
06/04/1900 12:15:1206/04/1900 12:15:12
Règles associéesRelated Rules
CA1305 : Spécifier IFormatProviderCA1305: Specify IFormatProvider
Voir aussiSee Also
À l’aide de la classe CultureInfoUsing the CultureInfo Class