Fix warnings found with CA1861 Avoid constant arrays as arguments (#86229)

* Fix warnings found with CA1861

* Update src/coreclr/tools/aot/ILCompiler/Program.cs

Co-authored-by: Stephen Toub <stoub@microsoft.com>

* Remove supression from static field

* Revert using string.Split(char)

* Update src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Dan Moseley <danmose@microsoft.com>
This commit is contained in:
Buyaa Namnan 2023-05-31 14:01:01 -07:00 committed by GitHub
parent ed2634403d
commit 5e67657e20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 197 additions and 107 deletions

View File

@ -471,6 +471,9 @@ dotnet_diagnostic.CA1859.severity = warning
# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = warning
# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.severity = warning
# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

View File

@ -468,6 +468,9 @@ dotnet_diagnostic.CA1859.severity = none
# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = none
# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.severity = none
# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

View File

@ -267,9 +267,11 @@ namespace ILCompiler
// + the original command line arguments
// + a rsp file that should work to directly run out of the zip file
#pragma warning disable CA1861 // Avoid constant arrays as arguments. Only executed once during the execution of the program.
Helpers.MakeReproPackage(makeReproPath, context.ParseResult.GetValue(OutputFilePath), args, context.ParseResult,
inputOptions : new[] { "r", "reference", "m", "mibc", "rdxml", "directpinvokelist", "descriptor" },
outputOptions : new[] { "o", "out", "exportsfile" });
#pragma warning restore CA1861 // Avoid constant arrays as arguments
}
context.ExitCode = new Program(this).Run();

View File

@ -29,6 +29,7 @@ namespace ILCompiler
internal sealed class Program
{
private readonly ILCompilerRootCommand _command;
private static readonly char[] s_separator = new char[] { ',', ';', ' ' };
public Program(ILCompilerRootCommand command)
{
@ -682,7 +683,7 @@ namespace ILCompiler
{
foreach (string value in warningCodes)
{
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
string[] values = value.Split(s_separator, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code))

View File

@ -11,6 +11,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
internal sealed class IDispatchMetaObject : ComFallbackMetaObject
{
private readonly IDispatchComObject _self;
private static readonly bool[] s_false = new bool[] { false };
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
internal IDispatchMetaObject(Expression expression, IDispatchComObject self)
@ -218,7 +219,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
DynamicMetaObject result = new ComInvokeBinder(
new CallInfo(1),
new[] { value },
new bool[] { false },
s_false,
restrictions,
Expression.Constant(method),
dispatch,

View File

@ -49,6 +49,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
// Don't need a dictionary for this, it will have very few elements
// (guaranteed less than 28, in practice 0-2)
private static readonly List<Type> s_generatedTypes = new List<Type>(0);
private static readonly string[] s_genericTName = new string[] { "T" };
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray1))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray2))]
@ -100,7 +101,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
{
TypeAttributes attrs = TypeAttributes.NotPublic | TypeAttributes.SequentialLayout;
TypeBuilder type = UnsafeMethods.DynamicModule.DefineType("VariantArray" + size, attrs, typeof(ValueType));
GenericTypeParameterBuilder T = type.DefineGenericParameters(new string[] { "T" })[0];
GenericTypeParameterBuilder T = type.DefineGenericParameters(s_genericTName)[0];
for (int i = 0; i < size; i++)
{
type.DefineField("Element" + i, T, FieldAttributes.Public);

View File

@ -1151,7 +1151,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
CType arrayType = (ArrayType)TypeManager.SubstType(mp.Params[mp.Params.Count - 1], type, pTypeArgs);
// Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work.
ExprArrayInit arrayInit = ExprFactory.CreateArrayInit(arrayType, null, null, new[] { 0 });
ExprArrayInit arrayInit = ExprFactory.CreateArrayInit(arrayType, null, null, s_zero);
arrayInit.GeneratedForParamArray = true;
arrayInit.OptionalArguments = named.Value;
@ -1229,7 +1229,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
CType elementType = subArr.ElementType;
// Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work.
ExprArrayInit exprArrayInit = ExprFactory.CreateArrayInit(substitutedArrayType, null, null, new[] { 0 });
ExprArrayInit exprArrayInit = ExprFactory.CreateArrayInit(substitutedArrayType, null, null, s_zero);
exprArrayInit.GeneratedForParamArray = true;
if (it.AtEnd())
@ -1618,6 +1618,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private AggregateSymbol ContextForMemberLookup => Context.ContextForMemberLookup;
private static readonly int[] s_zero = new[] { 0 };
private static ExprWrap WrapShortLivedExpression(Expr expr) => ExprFactory.CreateWrap(expr);
private static ExprAssignment GenerateOptimizedAssignment(Expr op1, Expr op2) => ExprFactory.CreateAssignment(op1, op2);

View File

@ -20,6 +20,8 @@ namespace Microsoft.Extensions.DependencyModel
public IEnumerable<string> NonApplicationPaths { get; }
private static readonly char[] s_semicolon = new[] { ';' };
public DependencyContextPaths(
string? application,
string? sharedRuntime,
@ -40,7 +42,7 @@ namespace Microsoft.Extensions.DependencyModel
internal static DependencyContextPaths Create(string? depsFiles, string? sharedRuntime)
{
string[]? files = depsFiles?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[]? files = depsFiles?.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
string? application = files != null && files.Length > 0 ? files[0] : null;
string[]? nonApplicationPaths = files?

View File

@ -117,6 +117,8 @@ namespace Microsoft.Extensions.Logging.EventSource
private const string UseAppFilters = "UseAppFilters";
private const string WriteEventCoreSuppressionJustification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.";
private const string WriteEventDynamicDependencySuppressionJustification = "DynamicDependency attribute will ensure that the required properties are not trimmed.";
private static readonly char[] s_semicolon = new[] { ';' };
private static readonly char[] s_colon = new[] { ':' };
private LoggingEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat)
{
@ -366,7 +368,7 @@ namespace Microsoft.Extensions.Logging.EventSource
var rules = new List<LoggerFilterRule>();
int ruleStringsStartIndex = 0;
string[] ruleStrings = filterSpec.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] ruleStrings = filterSpec.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
if (ruleStrings.Length > 0 && ruleStrings[0].Equals(UseAppFilters, StringComparison.OrdinalIgnoreCase))
{
// Avoid adding default rule to disable event source loggers
@ -381,7 +383,7 @@ namespace Microsoft.Extensions.Logging.EventSource
{
string rule = ruleStrings[i];
LogLevel level = defaultLevel;
string[] parts = rule.Split(new[] { ':' }, 2);
string[] parts = rule.Split(s_colon, 2);
string loggerName = parts[0];
if (loggerName.Length == 0)
{

View File

@ -33,6 +33,8 @@ namespace System.Data.OleDb
}
}
private static readonly char[] s_trimChars = new char[] { '@', ' ', ':' };
private void OleDbRowUpdatingHandler(object sender, OleDbRowUpdatingEventArgs ruevent)
{
RowUpdatingHandler(ruevent);
@ -235,7 +237,7 @@ namespace System.Data.OleDb
if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default))
{
// $CONSIDER - not trimming the @ from the beginning but to left the designer do that
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(new char[] { '@', ' ', ':' });
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(s_trimChars);
}
if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default))
{

View File

@ -175,6 +175,8 @@ namespace System.Data.OleDb
}
}
internal static readonly char[] s_comma = new char[] { ',' };
// grouping the native OLE DB casts togther by required interfaces and optional interfaces, connection then session
// want these to be methods, not properties otherwise they appear in VS7 managed debugger which attempts to evaluate them
@ -475,7 +477,7 @@ namespace System.Data.OleDb
if (null != keywords)
{
string[] values = keywords.Split(new char[1] { ',' });
string[] values = keywords.Split(s_comma);
for (int i = 0; i < values.Length; ++i)
{
DataRow row = table.NewRow();

View File

@ -629,7 +629,7 @@ namespace System.Data.OleDb
if (svalue.IndexOf(',') != -1)
{
int convertedValue = 0;
string[] values = svalue.Split(new char[] { ',' });
string[] values = svalue.Split(OleDbConnectionInternal.s_comma);
foreach (string v in values)
{
convertedValue |= (int)Enum.Parse<OleDbServiceValues>(v, true);

View File

@ -494,7 +494,7 @@ namespace System.DirectoryServices.AccountManagement
// even before we call ObjectSecurity to see if it would return null, because once ObjectSecurity returns null the
// first time, it'll keep returning null even if we refresh the cache.
if (!de.Properties.Contains("nTSecurityDescriptor"))
de.RefreshCache(new string[] { "nTSecurityDescriptor" });
de.RefreshCache(s_nTSecurityDescriptor);
ActiveDirectorySecurity adsSecurity = de.ObjectSecurity;
bool denySelfFound;
@ -829,7 +829,7 @@ namespace System.DirectoryServices.AccountManagement
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
de.RefreshCache(new string[] { "msDS-User-Account-Control-Computed", "lockoutTime" });
de.RefreshCache(s_msDSUACCLockoutTime);
if (de.Properties["msDS-User-Account-Control-Computed"].Count > 0)
{
@ -992,31 +992,31 @@ namespace System.DirectoryServices.AccountManagement
internal override ResultSet FindByLockoutTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "lockoutTime" }, matchType, dt);
return FindByDate(principalType, s_lockoutTime, matchType, dt);
}
internal override ResultSet FindByLogonTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "lastLogon", "lastLogonTimestamp" }, matchType, dt);
return FindByDate(principalType, s_lastLogonTime, matchType, dt);
}
internal override ResultSet FindByPasswordSetTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "pwdLastSet" }, matchType, dt);
return FindByDate(principalType, s_pwdLastSet, matchType, dt);
}
internal override ResultSet FindByBadPasswordAttempt(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "badPasswordTime" }, matchType, dt);
return FindByDate(principalType, s_badPasswordTime, matchType, dt);
}
internal override ResultSet FindByExpirationTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "accountExpires" }, matchType, dt);
return FindByDate(principalType, s_accountExpires, matchType, dt);
}
private ADEntriesSet FindByDate(Type subtype, string[] ldapAttributes, MatchType matchType, DateTime value)
@ -1300,7 +1300,7 @@ namespace System.DirectoryServices.AccountManagement
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetGroupsMemberOf: principalDN={0}", principalDN);
principalDE.RefreshCache(new string[] { "memberOf", "primaryGroupID" });
principalDE.RefreshCache(s_memberOfPrimaryGroupId);
if ((principalDE.Properties["primaryGroupID"].Count > 0) &&
(principalDE.Properties["objectSid"].Count > 0))
@ -2386,6 +2386,16 @@ namespace System.DirectoryServices.AccountManagement
protected string contextBasePartitionDN; //contains the DN of the Partition to which the user supplied context base (this.ctxBase) belongs.
protected string dnsHostName;
protected ulong lockoutDuration;
private static readonly string[] s_lockoutTime = new string[] { "lockoutTime" };
private static readonly string[] s_lastLogonTime = new string[] { "lastLogon", "lastLogonTimestamp" };
private static readonly string[] s_pwdLastSet = new string[] { "pwdLastSet" };
private static readonly string[] s_badPasswordTime = new string[] { "badPasswordTime" };
private static readonly string[] s_accountExpires = new string[] { "accountExpires" };
private static readonly string[] s_nTSecurityDescriptor = new string[] { "nTSecurityDescriptor" };
private static readonly string[] s_msDSUACCLockoutTime = new string[] { "msDS-User-Account-Control-Computed", "lockoutTime" };
private static readonly string[] s_memberOfPrimaryGroupId = new string[] { "memberOf", "primaryGroupID" };
private static readonly string[] s_lockoutDuration = new string[] { "lockoutDuration" };
internal static readonly char[] s_comma = new char[] { ',' };
protected enum StoreCapabilityMap
{
@ -2415,7 +2425,7 @@ namespace System.DirectoryServices.AccountManagement
this.contextBasePartitionDN = this.defaultNamingContext;
// Split the naming context's DN into its RDNs
string[] ncComponents = defaultNamingContext.Split(new char[] { ',' });
string[] ncComponents = defaultNamingContext.Split(s_comma);
StringBuilder sb = new StringBuilder();
@ -2492,7 +2502,7 @@ namespace System.DirectoryServices.AccountManagement
this.authTypes);
// So we don't load every property
domainNC.RefreshCache(new string[] { "lockoutDuration" });
domainNC.RefreshCache(s_lockoutDuration);
if (domainNC.Properties["lockoutDuration"].Count > 0)
{

View File

@ -904,7 +904,7 @@ namespace System.DirectoryServices.AccountManagement
Debug.Assert(values[0] is string);
string commaSeparatedValues = (string)values[0];
string[] individualValues = commaSeparatedValues.Split(new char[] { ',' });
string[] individualValues = commaSeparatedValues.Split(s_comma);
// ValueCollection<string> is Load'ed from a List<string>
List<string> list = new List<string>(individualValues.Length);
@ -1078,7 +1078,7 @@ namespace System.DirectoryServices.AccountManagement
// first time, it'll keep returning null even if we refresh the cache.
if (!de.Properties.Contains("nTSecurityDescriptor"))
de.RefreshCache(new string[] { "nTSecurityDescriptor" });
de.RefreshCache(s_nTSecurityDescriptor);
ActiveDirectorySecurity adsSecurity = de.ObjectSecurity;
@ -1637,6 +1637,8 @@ namespace System.DirectoryServices.AccountManagement
}
}
private static readonly string[] s_objectSid = new string[] { "objectSid" };
// Builds a SID dn for the principal <SID=...>
protected static string GetSidPathFromPrincipal(Principal p)
{
@ -1661,7 +1663,7 @@ namespace System.DirectoryServices.AccountManagement
// Force it to load if it hasn't been already loaded
if (!de.Properties.Contains("objectSid"))
de.RefreshCache(new string[] { "objectSid" });
de.RefreshCache(s_objectSid);
byte[] sid = (byte[])de.Properties["objectSid"].Value;

View File

@ -780,7 +780,7 @@ namespace System.DirectoryServices.AccountManagement
internal static string ConstructDnsDomainNameFromDn(string dn)
{
// Split the DN into its RDNs
string[] ncComponents = dn.Split(new char[] { ',' });
string[] ncComponents = dn.Split(ADStoreCtx.s_comma);
StringBuilder sb = new StringBuilder();

View File

@ -348,6 +348,8 @@ namespace System.DirectoryServices.AccountManagement
/// </summary>
internal SearchResult SmallGroupMemberSearchResult { get; private set; }
private static readonly string[] s_member = new string[] { "member" };
/// <summary>
/// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500)
/// The property list for the searcher of a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute
@ -366,7 +368,7 @@ namespace System.DirectoryServices.AccountManagement
Debug.Assert(de != null);
if (de != null)
{
using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base))
using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", s_member, SearchScope.Base))
{
SearchResult sr = ds.FindOne();
if (sr != null)

View File

@ -18,6 +18,8 @@ namespace System.DirectoryServices.AccountManagement
return string.Equals(de.SchemaClassName, classToCompare, StringComparison.OrdinalIgnoreCase);
}
internal static readonly char[] s_dot = new char[] { '.' };
internal static bool GetOSVersion(DirectoryEntry computerDE, out int versionMajor, out int versionMinor)
{
Debug.Assert(SAMUtils.IsOfObjectClass(computerDE, "Computer"));
@ -56,7 +58,7 @@ namespace System.DirectoryServices.AccountManagement
//
// We'll split the string into its period-separated components, and parse
// each component into an int.
string[] versionComponents = version.Split(new char[] { '.' });
string[] versionComponents = version.Split(s_dot);
Debug.Assert(versionComponents.Length >= 1); // since version was a non-empty string

View File

@ -27,6 +27,7 @@ namespace System.DirectoryServices.ActiveDirectory
private IntPtr _authIdentity = IntPtr.Zero;
private SyncUpdateCallback? _userDelegate;
private readonly SyncReplicaFromAllServersCallback _syncAllFunctionPointer;
private static readonly char[] s_comma = new char[] { ',' };
#region constructors
internal AdamInstance(DirectoryContext context, string adamInstanceName)
@ -707,7 +708,7 @@ namespace System.DirectoryServices.ActiveDirectory
// get the site object name from the server object name
// CN=server1,CN=Servers,CN=Site1,CN=Sites
// the site object name is the third component onwards
string[] components = ServerObjectName.Split(new char[] { ',' });
string[] components = ServerObjectName.Split(s_comma);
if (components.GetLength(0) < 3)
{
// should not happen

View File

@ -74,7 +74,7 @@ namespace System.DirectoryServices.ActiveDirectory
try
{
de.RefreshCache(new string[] { "options" });
de.RefreshCache(s_options);
}
catch (COMException e)
{
@ -223,7 +223,7 @@ namespace System.DirectoryServices.ActiveDirectory
ADSearcher adSearcher = new ADSearcher(_cachedEntry,
"(&(objectClass=siteLink)(objectCategory=SiteLink))",
new string[] { "cn" },
s_cn,
SearchScope.OneLevel);
SearchResultCollection? results = null;
@ -271,7 +271,7 @@ namespace System.DirectoryServices.ActiveDirectory
ADSearcher adSearcher = new ADSearcher(_cachedEntry,
"(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge))",
new string[] { "cn" },
s_cn,
SearchScope.OneLevel);
SearchResultCollection? results = null;
@ -307,6 +307,9 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
private static readonly string[] s_options = new string[] { "options" };
private static readonly string[] s_cn = new string[] { "cn" };
public void Save()
{
if (_disposed)

View File

@ -91,7 +91,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=site)(objectCategory=site)(name=" + Utils.GetEscapedFilterValue(siteName) + "))",
new string[] { "distinguishedName" },
s_distinguishedName,
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */);
@ -709,6 +709,14 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
internal static readonly string[] s_distinguishedName = new string[] { "distinguishedName" };
private static readonly string[] s_propertiesToLoadArray = new string[] { "fromServer", "distinguishedName", "dNSHostName", "objectCategory" };
private static readonly string[] s_cnLocation = new string[] { "cn", "location" };
private static readonly string[] s_cnDistinguishedName = new string[] { "cn", "distinguishedName" };
private static readonly string[] s_dNSHostName = new string[] { "dNSHostName" };
private static readonly string[] s_fromServerDistinguishedName = new string[] { "fromServer", "distinguishedName" };
private static readonly string[] s_dNSHostNameDistinguishedName = new string[] { "dNSHostName", "distinguishedName" };
public void Save()
{
if (_disposed)
@ -898,7 +906,7 @@ namespace System.DirectoryServices.ActiveDirectory
// go through connection objects and find out its fromServer property.
ADSearcher adSearcher = new ADSearcher(de,
"(|(objectCategory=server)(objectCategory=NTDSConnection))",
new string[] { "fromServer", "distinguishedName", "dNSHostName", "objectCategory" },
s_propertiesToLoadArray,
SearchScope.Subtree,
true, /* need paged search */
true /* need cached result as we need to go back to the first record */);
@ -989,7 +997,7 @@ namespace System.DirectoryServices.ActiveDirectory
str.Append(')');
ADSearcher adSearcher = new ADSearcher(serverEntry,
"(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)" + str.ToString() + ")",
new string[] { "fromServer", "distinguishedName" },
s_fromServerDistinguishedName,
SearchScope.Subtree);
SearchResultCollection? conResults = null;
try
@ -1132,7 +1140,7 @@ namespace System.DirectoryServices.ActiveDirectory
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=subnet)(objectCategory=subnet)(siteObject=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)!) + "))",
new string[] { "cn", "location" },
s_cnLocation,
SearchScope.OneLevel
);
SearchResultCollection? results = null;
@ -1176,7 +1184,7 @@ namespace System.DirectoryServices.ActiveDirectory
de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)!) + "))",
new string[] { "cn", "distinguishedName" },
s_cnDistinguishedName,
SearchScope.Subtree);
SearchResultCollection? results = null;
@ -1244,7 +1252,7 @@ namespace System.DirectoryServices.ActiveDirectory
de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)!) + "))",
new string[] { "cn", "distinguishedName" },
s_cnDistinguishedName,
SearchScope.Subtree);
SearchResultCollection? results = null;
@ -1359,7 +1367,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
ADSearcher adSearcher = new ADSearcher(cachedEntry,
"(&(objectClass=server)(objectCategory=server))",
new string[] { "dNSHostName" },
s_dNSHostName,
SearchScope.Subtree);
SearchResultCollection? results = null;
try
@ -1427,7 +1435,7 @@ namespace System.DirectoryServices.ActiveDirectory
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainerDN);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=server)(objectCategory=Server)(bridgeheadTransportList=" + Utils.GetEscapedFilterValue(transportDN) + "))",
new string[] { "dNSHostName", "distinguishedName" },
s_dNSHostNameDistinguishedName,
SearchScope.OneLevel);
SearchResultCollection? results = null;

View File

@ -149,7 +149,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLink)(objectCategory=SiteLink)(name=" + Utils.GetEscapedFilterValue(siteLinkName) + "))",
new string[] { "distinguishedName" },
ActiveDirectorySite.s_distinguishedName,
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */

View File

@ -136,7 +136,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge)(name=" + Utils.GetEscapedFilterValue(bridgeName) + "))",
new string[] { "distinguishedName" },
ActiveDirectorySite.s_distinguishedName,
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */);

View File

@ -47,7 +47,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=subnet)(objectCategory=subnet)(name=" + Utils.GetEscapedFilterValue(subnetName) + "))",
new string[] { "distinguishedName" },
ActiveDirectorySite.s_distinguishedName,
SearchScope.OneLevel,
false, /* don't need paged search */
false /* don't need to cache result */);

View File

@ -279,6 +279,10 @@ namespace System.DirectoryServices.ActiveDirectory
internal DirectoryContext Context => context;
private static readonly string[] s_name = new string[] { "name" };
private static readonly string[] s_cn = new string[] { "cn" };
private static readonly string[] s_objectClassCn = new string[] { "objectClass", "cn" };
internal unsafe void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle)
{
// call DsReplicaConsistencyCheck
@ -356,7 +360,7 @@ namespace System.DirectoryServices.ActiveDirectory
DirectoryEntry verifyEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, partition);
try
{
verifyEntry.RefreshCache(new string[] { "name" });
verifyEntry.RefreshCache(s_name);
}
catch (COMException e)
{
@ -769,7 +773,7 @@ namespace System.DirectoryServices.ActiveDirectory
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection))",
new string[] { "cn" },
s_cn,
SearchScope.OneLevel);
SearchResultCollection? srchResults = null;
@ -808,7 +812,7 @@ namespace System.DirectoryServices.ActiveDirectory
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection)(fromServer=CN=NTDS Settings," + serverName + "))",
new string[] { "objectClass", "cn" },
s_objectClassCn,
SearchScope.Subtree);
SearchResultCollection? results = null;

View File

@ -53,7 +53,7 @@ namespace System.DirectoryServices.ActiveDirectory
// doing the search to find the connection object based on its name
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=" + Utils.GetEscapedFilterValue(name) + "))",
new string[] { "distinguishedName" },
ActiveDirectorySite.s_distinguishedName,
SearchScope.OneLevel,
false, /* no paged search */
false /* don't cache results */);

View File

@ -896,7 +896,7 @@ namespace System.DirectoryServices.ActiveDirectory
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSDSA)(invocationID=" + stringGuid + "))",
new string[] { "distinguishedName" },
ActiveDirectorySite.s_distinguishedName,
SearchScope.Subtree,
false, /* don't need paged search */
false /* don't need to cache result */);

View File

@ -868,6 +868,9 @@ namespace System.Net
}
}
private static readonly char[] s_whitespaceDot = new char[] { ' ', '.', '\r', '\n' };
private static readonly char[] s_spaceCommaBrackets = new char[] { ' ', '(', ',', ')' };
/// <summary>
/// <para>Parses a response string for content length</para>
/// </summary>
@ -885,26 +888,28 @@ namespace System.Net
private DateTime GetLastModifiedFrom213Response(string str)
{
DateTime dateTime = _lastModified;
string[] parsedList = str.Split(new char[] { ' ', '.' });
if (parsedList.Length < 2)
Span<Range> parts = stackalloc Range[4];
ReadOnlySpan<char> strSpan = str;
int count = strSpan.SplitAny(parts, " .");
if (count < 2)
{
return dateTime;
}
string dateTimeLine = parsedList[1];
ReadOnlySpan<char> dateTimeLine = strSpan[parts[1]];
if (dateTimeLine.Length < 14)
{
return dateTime;
}
int year = Convert.ToInt32(dateTimeLine.Substring(0, 4), NumberFormatInfo.InvariantInfo);
int month = Convert.ToInt16(dateTimeLine.Substring(4, 2), NumberFormatInfo.InvariantInfo);
int day = Convert.ToInt16(dateTimeLine.Substring(6, 2), NumberFormatInfo.InvariantInfo);
int hour = Convert.ToInt16(dateTimeLine.Substring(8, 2), NumberFormatInfo.InvariantInfo);
int minute = Convert.ToInt16(dateTimeLine.Substring(10, 2), NumberFormatInfo.InvariantInfo);
int second = Convert.ToInt16(dateTimeLine.Substring(12, 2), NumberFormatInfo.InvariantInfo);
int year = int.Parse(dateTimeLine.Slice(0, 4), NumberFormatInfo.InvariantInfo);
int month = short.Parse(dateTimeLine.Slice(4, 2), NumberFormatInfo.InvariantInfo);
int day = short.Parse(dateTimeLine.Slice(6, 2), NumberFormatInfo.InvariantInfo);
int hour = short.Parse(dateTimeLine.Slice(8, 2), NumberFormatInfo.InvariantInfo);
int minute = short.Parse(dateTimeLine.Slice(10, 2), NumberFormatInfo.InvariantInfo);
int second = short.Parse(dateTimeLine.Slice(12, 2), NumberFormatInfo.InvariantInfo);
int millisecond = 0;
if (parsedList.Length > 2)
if (count > 2)
{
millisecond = Convert.ToInt16(parsedList[2], NumberFormatInfo.InvariantInfo);
millisecond = short.Parse(strSpan[parts[2]], NumberFormatInfo.InvariantInfo);
}
try
{
@ -941,12 +946,10 @@ namespace System.Net
if (end <= start)
return;
string filename = str.Substring(start, end - start);
filename = filename.TrimEnd(new char[] { ' ', '.', '\r', '\n' });
string filename = str.AsSpan(start, end - start).TrimEnd(s_whitespaceDot).ToString();
// Do minimal escaping that we need to get a valid Uri
// when combined with the baseUri
string escapedFilename;
escapedFilename = filename.Replace("%", "%25");
string escapedFilename = filename.Replace("%", "%25");
escapedFilename = escapedFilename.Replace("#", "%23");
// help us out if the user forgot to add a slash to the directory name
@ -1022,7 +1025,7 @@ namespace System.Net
/// </summary>
private static int GetPortV4(string responseString)
{
string[] parsedList = responseString.Split(new char[] { ' ', '(', ',', ')' });
string[] parsedList = responseString.Split(s_spaceCommaBrackets);
// We need at least the status code and the port
if (parsedList.Length <= 7)

View File

@ -2173,6 +2173,8 @@ namespace System.Diagnostics.Tracing
#endif // FEATURE_MANAGED_ETW || FEATURE_PERFTRACING
}
private static ReadOnlyCollection<string>? s_errorPayloadNames;
/// <summary>
/// Since this is a means of reporting errors (see ReportoutOfBandMessage) any failure encountered
/// while writing the message to any one of the listeners will be silently ignored.
@ -2184,7 +2186,7 @@ namespace System.Diagnostics.Tracing
EventName = eventName,
Message = msg,
Payload = new ReadOnlyCollection<object?>(new object[] { msg }),
PayloadNames = new ReadOnlyCollection<string>(new string[] { "message" })
PayloadNames = s_errorPayloadNames ??= new ReadOnlyCollection<string>(new string[] { "message" })
};
for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)

View File

@ -2596,7 +2596,7 @@ namespace System.Xml.Schema
{
if (getParticles)
{
string ContinuationString = SR.Format(SR.Sch_ContinuationString, new string[] { " " });
string ContinuationString = SR.Format(SR.Sch_ContinuationString, " ");
XmlSchemaParticle? currentParticle;
XmlSchemaParticle? nextParticle = null;
XmlQualifiedName currentQName;

View File

@ -65,6 +65,15 @@ namespace System.Xml.Serialization
}
internal TypeAttributes TypeAttributes { get { return _typeAttributes; } }
private static readonly string[] s_typeString = new string[] { "type" };
private static readonly string[] s_xmlReaderString = new string[] { "xmlReader" };
private static readonly string[] s_objectToSerializeWriterString = new string[] { "objectToSerialize", "writer" };
private static readonly string[] s_readerString = new string[] { "reader" };
private static readonly Type[] s_typeType = new Type[] { typeof(Type) };
private static readonly Type[] s_xmlReaderType = new Type[] { typeof(XmlReader) };
private static readonly Type[] s_objectXmlSerializationWriterType = new Type[] { typeof(object), typeof(XmlSerializationWriter) };
private static readonly Type[] s_xmlSerializationReaderType = new Type[] { typeof(XmlSerializationReader) };
internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName,
MethodAttributes attributes, Type? returnType, Type[] parameterTypes)
{
@ -228,8 +237,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(bool),
"CanSerialize",
new Type[] { typeof(Type) },
new string[] { "type" },
s_typeType,
s_typeString,
CodeGenerator.PublicOverrideMethodAttributes);
var uniqueTypes = new HashSet<Type>();
for (int i = 0; i < types.Length; i++)
@ -323,8 +332,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(bool),
"CanDeserialize",
new Type[] { typeof(XmlReader) },
new string[] { "xmlReader" },
s_xmlReaderType,
s_xmlReaderString,
CodeGenerator.PublicOverrideMethodAttributes
);
@ -358,8 +367,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(void),
"Serialize",
new Type[] { typeof(object), typeof(XmlSerializationWriter) },
new string[] { "objectToSerialize", "writer" },
s_objectXmlSerializationWriterType,
s_objectToSerializeWriterString,
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod(
writeMethod,
@ -382,8 +391,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(object),
"Deserialize",
new Type[] { typeof(XmlSerializationReader) },
new string[] { "reader" },
s_xmlSerializationReaderType,
s_readerString,
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod(
readMethod,
@ -436,8 +445,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(XmlSerializer),
"GetSerializer",
new Type[] { typeof(Type) },
new string[] { "type" },
s_typeType,
s_typeString,
CodeGenerator.PublicOverrideMethodAttributes);
for (int i = 0; i < xmlMappings.Length; i++)

View File

@ -26,6 +26,9 @@ namespace System.Xml.Serialization
internal Dictionary<string, EnumMapping> Enums => _enums ??= new Dictionary<string, EnumMapping>();
private static readonly string[] s_checkTypeString = new string[] { "checkType" };
private static readonly Type[] s_boolType = new Type[] { typeof(bool) };
private sealed class Member
{
private readonly string _source;
@ -503,7 +506,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod(
"set_IsReturnValue",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
s_boolType
)!;
ilg.Ldarg(0);
ilg.Ldc(true);
@ -1289,8 +1292,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
nullableMapping.TypeDesc!.Type!,
GetMethodBuilder(methodName!),
new Type[] { typeof(bool) },
new string[] { "checkType" },
s_boolType,
s_checkTypeString,
CodeGenerator.PrivateMethodAttributes);
LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type!, "o");
@ -1525,7 +1528,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationReader_set_DecodeName = typeof(XmlSerializationReader).GetMethod(
"set_DecodeName",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
s_boolType
)!;
ilg.Ldarg(0);
ilg.Ldc(false);
@ -2559,7 +2562,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod(
"set_IsReturnValue",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
s_boolType
)!;
ilg.Ldarg(0);
ilg.Ldc(false);
@ -3015,7 +3018,7 @@ namespace System.Xml.Serialization
CodeGenerator.PrivateMethodAttributes,
// See WriteNullableMethod for different return type logic
element.Mapping.TypeDesc!.Type,
new Type[] { typeof(bool) }
s_boolType
);
ilg.Call(methodBuilder);
WriteSourceEnd(source, element.Mapping.TypeDesc.Type!);
@ -3209,7 +3212,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationReader_ReadXmlXXX = typeof(XmlSerializationReader).GetMethod(
isDoc ? "ReadXmlDocument" : "ReadXmlNode",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
s_boolType
)!;
ilg.Ldarg(0);
ilg.Ldc(element.Any ? false : true);

View File

@ -332,7 +332,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationWriter_WriteEndElement = typeof(XmlSerializationWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
s_objectType
)!;
object oVar = ilg.GetVariable(source);
ilg.Ldarg(0);
@ -353,6 +353,11 @@ namespace System.Xml.Serialization
WriteTag("WriteEmptyTag", name, ns);
}
private static readonly string[] s_argNamesP = new string[] { "p" };
private static readonly string[] s_argNamesO = new string[] { "o" };
private static readonly Type[] s_objectArrayType = new Type[] { typeof(object[]) };
private static readonly Type[] s_objectType = new Type[] { typeof(object) };
[RequiresUnreferencedCode("calls WriteMember")]
private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping)
{
@ -365,8 +370,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(void),
methodName,
new Type[] { typeof(object[]) },
new string[] { "p" },
s_objectArrayType,
s_argNamesP,
CodeGenerator.PublicMethodAttributes
);
@ -557,8 +562,8 @@ namespace System.Xml.Serialization
ilg.BeginMethod(
typeof(void),
methodName,
new Type[] { typeof(object) },
new string[] { "o" },
s_objectType,
s_argNamesO,
CodeGenerator.PublicMethodAttributes
);
@ -1004,7 +1009,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
s_objectType
)!;
ilg.Ldarg(0);
ilg.Ldarg(oArg);
@ -1849,7 +1854,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) })!;
s_objectType)!;
ilg.Ldarg(0);
source.Load(typeof(object));
ilg.Call(XmlSerializationWriter_CreateUnknownTypeException);
@ -2064,7 +2069,7 @@ namespace System.Xml.Serialization
MethodInfo XmlSerializationWriter_CreateInvalidAnyTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidAnyTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
s_objectType
)!;
ilg.Ldarg(0);
source.Load(null);

View File

@ -149,6 +149,8 @@ namespace System.Security.Cryptography.Xml
}
}
private static readonly string[] s_expectedAttrNames = new string[] { "Id", "URI", "Type" };
//
// public methods
//
@ -214,7 +216,7 @@ namespace System.Security.Cryptography.Xml
_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);
if (!Utils.VerifyAttributes(value, new string[] { "Id", "URI", "Type" }))
if (!Utils.VerifyAttributes(value, s_expectedAttrNames))
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference");
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

View File

@ -206,7 +206,8 @@ namespace System.Security.Cryptography
AddEntry("1.3.133.16.840.63.0.2", "ECDH_STD_SHA1_KDF");
AddEntry("1.3.132.1.11.1", "ECDH_STD_SHA256_KDF");
AddEntry("1.3.132.1.11.2", "ECDH_STD_SHA384_KDF");
AddEntry("1.2.840.10045.3.1.7", "ECDSA_P256", new[] { "nistP256", "secP256r1", "x962P256v1", "ECDH_P256" } );
#pragma warning disable CA1861 // Avoid constant arrays as arguments. Loaded by static constructor
AddEntry("1.2.840.10045.3.1.7", "ECDSA_P256", new[] { "nistP256", "secP256r1", "x962P256v1", "ECDH_P256" });
AddEntry("1.3.132.0.34", "ECDSA_P384", new[] { "nistP384", "secP384r1", "ECDH_P384" });
AddEntry("1.3.132.0.35", "ECDSA_P521", new[] { "nistP521", "secP521r1", "ECDH_P521" });
AddEntry("1.2.840.113549.1.9.16.3.5", "ESDH");
@ -236,6 +237,7 @@ namespace System.Security.Cryptography
AddEntry("1.2.840.113549.1.1.7", "RSAES_OAEP");
AddEntry("1.2.840.113549.1.1.10", "RSASSA-PSS");
AddEntry("2.5.4.8", "S", new[] { "ST" });
#pragma warning restore CA1861 // Avoid constant arrays as arguments
AddEntry("1.3.132.0.9", "secP160k1");
AddEntry("1.3.132.0.8", "secP160r1");
AddEntry("1.3.132.0.30", "secP160r2");

View File

@ -64,7 +64,7 @@ namespace System.Speech.Internal.ObjectTokens
}
// If the last character is a '\', get rid of it
registryPath = registryPath.Trim(new char[] { '\\' });
registryPath = registryPath.Trim('\\');
string rootPath = GetFirstKeyAndParseRemainder(ref registryPath);

View File

@ -277,7 +277,7 @@ namespace System.Speech.Internal.SrgsCompiler
/// </summary>
private static NameValuePair[] ParseInitParams(string initParameters)
{
string[] parameters = initParameters.Split(new char[] { ';' }, StringSplitOptions.None);
string[] parameters = initParameters.Split(';', StringSplitOptions.None);
NameValuePair[] pairs = new NameValuePair[parameters.Length];
for (int i = 0; i < parameters.Length; i++)

View File

@ -850,7 +850,7 @@ namespace System.Speech.Recognition
return Array.Empty<NameValuePair>();
}
string[] parameters = initParameters.Split(new char[] { ';' }, StringSplitOptions.None);
string[] parameters = initParameters.Split(';', StringSplitOptions.None);
NameValuePair[] pairs = new NameValuePair[parameters.Length];
for (int i = 0; i < parameters.Length; i++)

View File

@ -1404,7 +1404,7 @@ ISpGrammarResourceLoader
{
// If the base Uri has not been set any other way, then set the base Uri for this file
string uri = grammar.Uri.OriginalString;
int posSlash = uri.LastIndexOfAny(new char[] { '\\', '/' });
int posSlash = uri.LastIndexOfAny(s_slashes);
if (posSlash >= 0)
{
baseUri = new Uri(uri.Substring(0, posSlash + 1), UriKind.RelativeOrAbsolute);
@ -1489,7 +1489,7 @@ ISpGrammarResourceLoader
string ruleName = pbstrMIMEType;
// The parent is the first
string[] ids = pbstrRedirectUrl.Split(new char[] { ' ' }, StringSplitOptions.None);
string[] ids = pbstrRedirectUrl.Split(' ', StringSplitOptions.None);
System.Diagnostics.Debug.Assert(ids.Length == 2);
uint parentGrammarId = uint.Parse(ids[0], CultureInfo.InvariantCulture);
@ -3044,6 +3044,7 @@ ISpGrammarResourceLoader
private TimeSpan _defaultTimeout = TimeSpan.FromSeconds(30);
private RecognizerBaseThunk _recoThunk;
private static readonly char[] s_slashes = new char[] { '\\', '/' };
#endregion
private sealed class RecognizerBaseThunk : ISpGrammarResourceLoader

View File

@ -19,6 +19,7 @@ using Microsoft.CodeAnalysis.CSharp;
// Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations
// are concerned.
#pragma warning disable CA1861 // Avoid constant arrays as arguments.
namespace System.Text.RegularExpressions.Generator
{
public partial class RegexGenerator

View File

@ -34,6 +34,8 @@ namespace System.Text.RegularExpressions.Generator
/// <inheritdoc />
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticDescriptors.UseRegexSourceGeneration.Id);
private static readonly char[] s_comma = new[] { ',' };
public override FixAllProvider? GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
/// <inheritdoc />
@ -313,7 +315,7 @@ namespace System.Text.RegularExpressions.Generator
// Parse the runtime-generated "Option1, Option2" into each piece and then concat
// them back together.
string[] parts = stringifiedRegexOptions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = stringifiedRegexOptions.Split(s_comma, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
parts[i] = "RegexOptions." + parts[i].Trim();

View File

@ -41,7 +41,7 @@ namespace System.Reflection
// Why don't we just use "&"?
if (t.IsByRef)
{
sb.Append(typeName.TrimEnd(new char[] { '&' }));
sb.Append(typeName.TrimEnd('&'));
sb.Append(" ByRef");
}
else

View File

@ -72,7 +72,7 @@ internal sealed class BrowserHost
runArgsJson.Save(Path.Combine(_args.CommonConfig.AppPath, "runArgs.json"));
string[] urls = envVars.TryGetValue("ASPNETCORE_URLS", out string? aspnetUrls)
? aspnetUrls.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
? aspnetUrls.Split(';', StringSplitOptions.RemoveEmptyEntries)
: new string[] { $"http://127.0.0.1:{_args.CommonConfig.HostProperties.WebServerPort}", "https://127.0.0.1:0" };
(ServerURLs serverURLs, IWebHost host) = await StartWebServerAsync(_args.CommonConfig.AppPath,

View File

@ -2068,7 +2068,9 @@ namespace Mono.Options
command.Options.WriteOptionDescriptions(CommandSet.Out);
return 0;
}
#pragma warning disable CA1861 // Avoid constant arrays as arguments. Only invoked when --help is passed.
return command.Invoke(new[] { "--help" });
#pragma warning restore CA1861
}
private List<KeyValuePair<string, Command>> GetCommands()

View File

@ -47,7 +47,7 @@ internal sealed class WasmSymbolicator
int i = 0;
foreach (var line in File.ReadAllLines(symbolsMapFile))
{
string[] parts = line.Split(new char[] { ':' }, 2);
string[] parts = line.Split(':', 2);
if (parts.Length != 2)
{
_logger.LogWarning($"Unexpected symbol map format at line {i + 1} in {symbolsMapFile}");

View File

@ -291,6 +291,7 @@ public class MonoAOTCompiler : Microsoft.Build.Utilities.Task
private int _totalNumAssemblies;
private readonly Dictionary<string, string> _symbolNameFixups = new();
private static readonly char[] s_semicolon = new char[]{ ';' };
private bool ProcessAndValidateArguments()
{
@ -635,13 +636,13 @@ public class MonoAOTCompiler : Microsoft.Build.Utilities.Task
var a = assemblyItem.GetMetadata("AotArguments");
if (a != null)
{
aotArgs.AddRange(a.Split(new char[]{ ';' }, StringSplitOptions.RemoveEmptyEntries));
aotArgs.AddRange(a.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries));
}
var p = assemblyItem.GetMetadata("ProcessArguments");
if (p != null)
{
processArgs.AddRange(p.Split(new char[]{ ';' }, StringSplitOptions.RemoveEmptyEntries));
processArgs.AddRange(p.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries));
}
processArgs.Add("--debug");

View File

@ -346,7 +346,7 @@ namespace Microsoft.NET.Build.Tasks
if (!string.IsNullOrEmpty(Crossgen2ExtraCommandLineArgs))
{
foreach (string extraArg in Crossgen2ExtraCommandLineArgs.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries))
foreach (string extraArg in Crossgen2ExtraCommandLineArgs.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
result.AppendLine(extraArg);
}

View File

@ -42,6 +42,8 @@ namespace Microsoft.WebAssembly.Build.Tasks
private string? _tempPath;
private int _totalFiles;
private int _numCompiled;
private static readonly char[] s_semicolon = new char[] { ';' };
private static readonly char[] s_equalTo = new char[] { '=' };
public override bool Execute()
{
@ -90,7 +92,7 @@ namespace Microsoft.WebAssembly.Build.Tasks
string depMetadata = srcItem.GetMetadata("Dependencies");
string[] depFiles = string.IsNullOrEmpty(depMetadata)
? Array.Empty<string>()
: depMetadata.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
: depMetadata.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
if (!ShouldCompile(srcFile, objFile, depFiles, out string reason))
{
@ -299,7 +301,7 @@ namespace Microsoft.WebAssembly.Build.Tasks
foreach (var item in EnvironmentVariables)
{
var parts = item.ItemSpec.Split(new char[] {'='}, 2, StringSplitOptions.None);
var parts = item.ItemSpec.Split(s_equalTo, 2, StringSplitOptions.None);
if (parts.Length == 0)
continue;

View File

@ -85,6 +85,8 @@ namespace Mono.Linker
}
}
private static readonly char[] s_separators = new char[] { ',', ';', ' ' };
public Driver (Queue<string> arguments)
{
this.arguments = arguments;
@ -852,7 +854,7 @@ namespace Mono.Linker
}
value = Unquote (value);
string[] values = value.Split (new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
string[] values = value.Split (s_separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string v in values) {
var id = v.Trim ();
if (!id.StartsWith ("IL", StringComparison.Ordinal) || !ushort.TryParse (id.AsSpan (2), out ushort code))