未验证 提交 7508080e 编写于 作者: E Eric Erhardt 提交者: GitHub

Update coding-style to include target-typed new() guideline (#67061)

* Update coding-style to include target-typed new guideline

Similar to `var` usage, `new()` usage is only allowed when the Type can be understood from the same line.

Fix #53369

* Fix coding style violations
上级 0e1c91b6
......@@ -24,6 +24,7 @@ The general rule we follow is "use Visual Studio defaults".
9. If a file happens to differ in style from these guidelines (e.g. private members are named `m_member`
rather than `_member`), the existing style in that file takes precedence.
10. We only use `var` when the type is explicitly named on the right-hand side, typically due to either `new` or an explicit cast, e.g. `var stream = new FileStream(...)` not `var stream = OpenStandardInput()`.
- Similarly, target-typed `new()` can only be used when the type is explicitly named on the left-hand side, in a variable definition statement or a field definition statement. e.g. `FileStream stream = new(...);`, but not `stream = new(...);` (where the type was specified on a previous line).
11. We use language keywords instead of BCL types (e.g. `int, string, float` instead of `Int32, String, Single`, etc) for both type references as well as method calls (e.g. `int.Parse` instead of `Int32.Parse`). See issue [#13976](https://github.com/dotnet/runtime/issues/13976) for examples.
12. We use PascalCasing to name all our constant local variables and fields. The only exception is for interop code where the constant value should exactly match the name and value of the code you are calling via interop.
13. We use PascalCasing for all method names, including local functions.
......
......@@ -46,7 +46,7 @@ public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor!!, ILoggerFactor
_options = optionsAccessor.Value;
_logger = loggerFactory.CreateLogger<MemoryCache>();
_coherentState = new();
_coherentState = new CoherentState();
if (_options.Clock == null)
{
......
......@@ -165,7 +165,7 @@ internal static bool TryExtractBaggage(string baggageString, out IEnumerable<Key
if (keyStart < keyEnd && valueStart < currentIndex)
{
baggageList ??= new();
baggageList ??= new List<KeyValuePair<string, string?>>();
// Insert in reverse order for asp.net compatability.
baggageList.Insert(0, new KeyValuePair<string, string?>(
......
......@@ -70,7 +70,7 @@ public void AnimateAndCaptureFrames()
animation.Save(Path.Combine(testOutputFolder, $"{++frameIndexes[imageName]}_{timestamp}.jpg"), ImageFormat.Jpeg);
}));
bitmaps[imageName] = new(Helpers.GetTestBitmapPath(imageName));
bitmaps[imageName] = new Bitmap(Helpers.GetTestBitmapPath(imageName));
ImageAnimator.Animate(bitmaps[imageName], handlers[imageName]);
}
......
......@@ -139,7 +139,7 @@ internal string SubTypeComponent
/// This will return an enumerator over a dictionary of the parameter/value pairs.
/// </summary>
internal Dictionary<string, string>.Enumerator ParameterValuePairs =>
(_parameterDictionary ??= new()).GetEnumerator();
(_parameterDictionary ??= new Dictionary<string, string>()).GetEnumerator();
#endregion Internal Properties
#region Internal Methods
......@@ -330,7 +330,7 @@ private void ParseParameterAndValue(ReadOnlySpan<char> parameterAndValue)
//Get length of the parameter value
int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex);
(_parameterDictionary ??= new()).Add(
(_parameterDictionary ??= new Dictionary<string, string>()).Add(
ValidateToken(parameterAndValue.Slice(0, equalSignIndex).ToString()),
ValidateQuotedStringOrToken(parameterAndValue.Slice(parameterStartIndex, parameterValueLength).ToString()));
......
......@@ -841,7 +841,7 @@ internal void SetCallbackHandler(SafeHandle handle, Delegate del, IntPtr context
//
handle.DangerousAddRef(ref handle__addRefd);
IntPtr __handle_gen_native = handle.DangerousGetHandle();
__del_gen_native__marshaller = new(del);
__del_gen_native__marshaller = new AnyDelegateMarshaller(del);
IntPtr __del_gen_native = __del_gen_native__marshaller.Value;
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, void>)_functionPointer)(__handle_gen_native, __del_gen_native, context);
}
......@@ -929,7 +929,7 @@ internal uint RegistrationOpen(ref RegistrationConfig config, out SafeMsQuicRegi
//
// Marshal
//
__config_gen_native = new(config);
__config_gen_native = new RegistrationConfig.Native(config);
__retVal = ((delegate* unmanaged[Cdecl]<RegistrationConfig.Native*, IntPtr*, uint>)_functionPointer)(&__config_gen_native, &__registrationContext_gen_native);
__invokeSucceeded = true;
//
......@@ -1017,7 +1017,7 @@ internal uint ConfigurationLoadCredential(SafeMsQuicConfigurationHandle configur
//
configuration.DangerousAddRef(ref configuration__addRefd);
IntPtr __configuration_gen_native = configuration.DangerousGetHandle();
__credConfig_gen_native = new(credConfig);
__credConfig_gen_native = new CredentialConfig.Native(credConfig);
__retVal = ((delegate* unmanaged[Cdecl]<IntPtr, CredentialConfig.Native*, uint>)_functionPointer)(__configuration_gen_native, &__credConfig_gen_native);
//
// Unmarshal
......
......@@ -44,7 +44,7 @@ public async Task ReceiveHelloWithContextTakeover()
stream.Enqueue(0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00);
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
Memory<byte> buffer = new byte[5];
......@@ -74,7 +74,7 @@ public async Task SendHelloWithContextTakeover()
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken);
......@@ -95,7 +95,7 @@ public async Task SendHelloWithDisableCompression()
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
byte[] bytes = Encoding.UTF8.GetBytes("Hello");
......@@ -113,7 +113,7 @@ public async Task SendHelloWithEmptyFrame()
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
byte[] bytes = Encoding.UTF8.GetBytes("Hello");
......@@ -123,7 +123,7 @@ public async Task SendHelloWithEmptyFrame()
using WebSocket client = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
IsServer = false,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
ValueWebSocketReceiveResult result = await client.ReceiveAsync(bytes.AsMemory(), CancellationToken);
......@@ -141,7 +141,7 @@ public async Task ReceiveHelloWithoutContextTakeover()
WebSocketTestStream stream = new();
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientContextTakeover = false
}
......@@ -171,7 +171,7 @@ public async Task SendHelloWithoutContextTakeover()
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ServerContextTakeover = false
}
......@@ -196,7 +196,7 @@ public async Task TwoDeflateBlocksInOneMessage()
WebSocketTestStream stream = new();
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
// The first 3 octets(0xf2 0x48 0x05) and the least significant two
// bits of the 4th octet(0x00) constitute one DEFLATE block with
......@@ -285,14 +285,14 @@ public async Task LargeMessageSplitInMultipleFrames(int windowBits)
using WebSocket server = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientMaxWindowBits = windowBits
}
});
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientMaxWindowBits = windowBits
}
......@@ -466,7 +466,7 @@ public async Task SendReceiveWithDifferentWindowBits(int clientWindowBits, int s
using WebSocket server = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
{
IsServer = true,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientContextTakeover = false,
ClientMaxWindowBits = clientWindowBits,
......@@ -476,7 +476,7 @@ public async Task SendReceiveWithDifferentWindowBits(int clientWindowBits, int s
});
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientContextTakeover = false,
ClientMaxWindowBits = clientWindowBits,
......@@ -568,7 +568,7 @@ public async Task AutobahnTestCase13_3_1()
{
IsServer = true,
KeepAliveInterval = TimeSpan.Zero,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientMaxWindowBits = 9,
ServerMaxWindowBits = 9
......@@ -577,7 +577,7 @@ public async Task AutobahnTestCase13_3_1()
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
{
KeepAliveInterval = TimeSpan.Zero,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
{
ClientMaxWindowBits = 9,
ServerMaxWindowBits = 9
......@@ -609,7 +609,7 @@ public async Task CompressedMessageWithEmptyLastFrame()
{
IsServer = true,
KeepAliveInterval = TimeSpan.Zero,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
byte[] frame1 = new byte[1024];
......@@ -626,7 +626,7 @@ public async Task CompressedMessageWithEmptyLastFrame()
{
IsServer = false,
KeepAliveInterval = TimeSpan.Zero,
DangerousDeflateOptions = new()
DangerousDeflateOptions = new WebSocketDeflateOptions()
});
int messageSize = 0;
......
......@@ -209,7 +209,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second)
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59);
this = new DateTime(year, month, day, hour, minute, 59);
ValidateLeapSecond();
}
}
......@@ -226,7 +226,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, kind);
this = new DateTime(year, month, day, hour, minute, 59, kind);
ValidateLeapSecond();
}
}
......@@ -243,7 +243,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, calendar);
this = new DateTime(year, month, day, hour, minute, 59, calendar);
ValidateLeapSecond();
}
}
......@@ -265,7 +265,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, millisecond);
this = new DateTime(year, month, day, hour, minute, 59, millisecond);
ValidateLeapSecond();
}
}
......@@ -285,7 +285,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, millisecond, kind);
this = new DateTime(year, month, day, hour, minute, 59, millisecond, kind);
ValidateLeapSecond();
}
}
......@@ -302,7 +302,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, millisecond, calendar);
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar);
ValidateLeapSecond();
}
}
......@@ -320,7 +320,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new(year, month, day, hour, minute, 59, millisecond, calendar, kind);
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar, kind);
ValidateLeapSecond();
}
}
......
......@@ -389,11 +389,11 @@ private static NullableAttributeStateParser CreateParser(IList<CustomAttributeDa
attribute.AttributeType.Namespace == CompilerServicesNameSpace &&
attribute.ConstructorArguments.Count == 1)
{
return new(attribute.ConstructorArguments[0].Value);
return new NullableAttributeStateParser(attribute.ConstructorArguments[0].Value);
}
}
return new(null);
return new NullableAttributeStateParser(null);
}
private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability)
......
......@@ -99,7 +99,7 @@ private static Interop.BOOL HandlerRoutine(int dwCtrlType)
{
if (token.Signal == signal)
{
(tokens ??= new()).Add(token);
(tokens ??= new List<Token>()).Add(token);
}
}
}
......
......@@ -148,7 +148,7 @@ public IOCompletionPoller(nint port)
_nativeEvents =
(Interop.Kernel32.OVERLAPPED_ENTRY*)
NativeMemory.Alloc(NativeEventCapacity, (nuint)sizeof(Interop.Kernel32.OVERLAPPED_ENTRY));
_events = new(default);
_events = new ThreadPoolTypedWorkItemQueue<Event, Callback>(default);
// These threads don't run user code, use a smaller stack size
_thread = new Thread(Poll, SmallStackSizeBytes);
......
......@@ -41,7 +41,7 @@ public static IEnumerable<T> ToBlockingEnumerable<T>(this IAsyncEnumerable<T> so
if (!moveNextTask.IsCompleted)
{
(mres ??= new()).Wait(moveNextTask.ConfigureAwait(false).GetAwaiter());
(mres ??= new ManualResetEventWithAwaiterSupport()).Wait(moveNextTask.ConfigureAwait(false).GetAwaiter());
Debug.Assert(moveNextTask.IsCompleted);
}
......@@ -59,7 +59,7 @@ public static IEnumerable<T> ToBlockingEnumerable<T>(this IAsyncEnumerable<T> so
if (!disposeTask.IsCompleted)
{
(mres ?? new()).Wait(disposeTask.ConfigureAwait(false).GetAwaiter());
(mres ?? new ManualResetEventWithAwaiterSupport()).Wait(disposeTask.ConfigureAwait(false).GetAwaiter());
Debug.Assert(disposeTask.IsCompleted);
}
......
......@@ -158,7 +158,7 @@ public void GetValueRefOrNullRefValueType()
Assert.Equal(0, dict[1].Value);
Assert.Equal(0, dict[1].Property);
var itemVal = dict[1];
Struct itemVal = dict[1];
itemVal.Value = 1;
itemVal.Property = 2;
......@@ -172,7 +172,7 @@ public void GetValueRefOrNullRefValueType()
Assert.Equal(3, dict[1].Value);
Assert.Equal(4, dict[1].Property);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 2);
ref Struct itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 2);
Assert.Equal(0, itemRef.Value);
Assert.Equal(0, itemRef.Property);
......@@ -185,7 +185,7 @@ public void GetValueRefOrNullRefValueType()
Assert.Equal(dict[2].Value, itemRef.Value);
Assert.Equal(dict[2].Property, itemRef.Property);
itemRef = new() { Value = 7, Property = 8 };
itemRef = new Struct() { Value = 7, Property = 8 };
Assert.Equal(7, itemRef.Value);
Assert.Equal(8, itemRef.Property);
......@@ -205,8 +205,8 @@ public void GetValueRefOrNullRefClass()
{
var dict = new Dictionary<int, IntAsObject>
{
{ 1, new() },
{ 2, new() }
{ 1, new IntAsObject() },
{ 2, new IntAsObject() }
};
Assert.Equal(2, dict.Count);
......@@ -214,7 +214,7 @@ public void GetValueRefOrNullRefClass()
Assert.Equal(0, dict[1].Value);
Assert.Equal(0, dict[1].Property);
var itemVal = dict[1];
IntAsObject itemVal = dict[1];
itemVal.Value = 1;
itemVal.Property = 2;
......@@ -228,7 +228,7 @@ public void GetValueRefOrNullRefClass()
Assert.Equal(3, dict[1].Value);
Assert.Equal(4, dict[1].Property);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 2);
ref IntAsObject itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 2);
Assert.Equal(0, itemRef.Value);
Assert.Equal(0, itemRef.Property);
......@@ -241,7 +241,7 @@ public void GetValueRefOrNullRefClass()
Assert.Equal(dict[2].Value, itemRef.Value);
Assert.Equal(dict[2].Property, itemRef.Property);
itemRef = new() { Value = 7, Property = 8 };
itemRef = new IntAsObject() { Value = 7, Property = 8 };
Assert.Equal(7, itemRef.Value);
Assert.Equal(8, itemRef.Property);
......@@ -261,12 +261,12 @@ public void GetValueRefOrNullRefLinkBreaksOnResize()
{
var dict = new Dictionary<int, Struct>
{
{ 1, new() }
{ 1, new Struct() }
};
Assert.Equal(1, dict.Count);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 1);
ref Struct itemRef = ref CollectionsMarshal.GetValueRefOrNullRef(dict, 1);
Assert.Equal(0, itemRef.Value);
Assert.Equal(0, itemRef.Property);
......@@ -283,7 +283,7 @@ public void GetValueRefOrNullRefLinkBreaksOnResize()
dict.EnsureCapacity(100);
for (int i = 2; i <= 50; i++)
{
dict.Add(i, new());
dict.Add(i, new Struct());
}
itemRef.Value = 3;
......@@ -316,7 +316,7 @@ public void GetValueRefOrAddDefaultValueType()
Assert.Equal(0, dict[1].Value);
Assert.Equal(0, dict[1].Property);
var itemVal = dict[1];
Struct itemVal = dict[1];
itemVal.Value = 1;
itemVal.Property = 2;
......@@ -336,7 +336,7 @@ public void GetValueRefOrAddDefaultValueType()
Assert.Equal(3, dict[1].Value);
Assert.Equal(4, dict[1].Property);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 2, out exists);
ref Struct itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 2, out exists);
Assert.True(exists);
Assert.Equal(2, dict.Count);
......@@ -351,7 +351,7 @@ public void GetValueRefOrAddDefaultValueType()
Assert.Equal(dict[2].Value, itemRef.Value);
Assert.Equal(dict[2].Property, itemRef.Property);
itemRef = new() { Value = 7, Property = 8 };
itemRef = new Struct() { Value = 7, Property = 8 };
Assert.Equal(7, itemRef.Value);
Assert.Equal(8, itemRef.Property);
......@@ -360,7 +360,7 @@ public void GetValueRefOrAddDefaultValueType()
// Check for correct additions
ref var entry3Ref = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 3, out exists);
ref Struct entry3Ref = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 3, out exists);
Assert.False(exists);
Assert.Equal(3, dict.Count);
......@@ -370,7 +370,7 @@ public void GetValueRefOrAddDefaultValueType()
entry3Ref.Property = 42;
entry3Ref.Value = 12345;
var value3 = dict[3];
Struct value3 = dict[3];
Assert.Equal(42, value3.Property);
Assert.Equal(12345, value3.Value);
......@@ -381,8 +381,8 @@ public void GetValueRefOrAddDefaultClass()
{
var dict = new Dictionary<int, IntAsObject>
{
{ 1, new() },
{ 2, new() }
{ 1, new IntAsObject() },
{ 2, new IntAsObject() }
};
Assert.Equal(2, dict.Count);
......@@ -390,7 +390,7 @@ public void GetValueRefOrAddDefaultClass()
Assert.Equal(0, dict[1].Value);
Assert.Equal(0, dict[1].Property);
var itemVal = dict[1];
IntAsObject itemVal = dict[1];
itemVal.Value = 1;
itemVal.Property = 2;
......@@ -410,7 +410,7 @@ public void GetValueRefOrAddDefaultClass()
Assert.Equal(3, dict[1].Value);
Assert.Equal(4, dict[1].Property);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 2, out exists);
ref IntAsObject itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 2, out exists);
Assert.True(exists);
Assert.Equal(2, dict.Count);
......@@ -425,7 +425,7 @@ public void GetValueRefOrAddDefaultClass()
Assert.Equal(dict[2].Value, itemRef.Value);
Assert.Equal(dict[2].Property, itemRef.Property);
itemRef = new() { Value = 7, Property = 8 };
itemRef = new IntAsObject() { Value = 7, Property = 8 };
Assert.Equal(7, itemRef.Value);
Assert.Equal(8, itemRef.Property);
......@@ -434,16 +434,16 @@ public void GetValueRefOrAddDefaultClass()
// Check for correct additions
ref var entry3Ref = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 3, out exists);
ref IntAsObject entry3Ref = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 3, out exists);
Assert.False(exists);
Assert.Equal(3, dict.Count);
Assert.False(Unsafe.IsNullRef(ref entry3Ref));
Assert.Null(entry3Ref);
entry3Ref = new() { Value = 12345, Property = 42 };
entry3Ref = new IntAsObject() { Value = 12345, Property = 42 };
var value3 = dict[3];
IntAsObject value3 = dict[3];
Assert.Equal(42, value3.Property);
Assert.Equal(12345, value3.Value);
......@@ -454,12 +454,12 @@ public void GetValueRefOrAddDefaultLinkBreaksOnResize()
{
var dict = new Dictionary<int, Struct>
{
{ 1, new() }
{ 1, new Struct() }
};
Assert.Equal(1, dict.Count);
ref var itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 1, out bool exists);
ref Struct itemRef = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, 1, out bool exists);
Assert.True(exists);
Assert.Equal(1, dict.Count);
......@@ -478,7 +478,7 @@ public void GetValueRefOrAddDefaultLinkBreaksOnResize()
dict.EnsureCapacity(100);
for (int i = 2; i <= 50; i++)
{
dict.Add(i, new());
dict.Add(i, new Struct());
}
itemRef.Value = 3;
......
......@@ -1284,7 +1284,7 @@ public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R(Date
public static IEnumerable<object[]> ParseExact_TestData_R()
{
// Lowest, highest, and random DateTime in lower, upper, and normal casing
var pairs = new(DateTime, string)[]
var pairs = new (DateTime, string)[]
{
(DateTime.MaxValue, "Fri, 31 Dec 9999 23:59:59"),
(DateTime.MinValue, "Mon, 01 Jan 0001 00:00:00"),
......
......@@ -223,7 +223,7 @@ public void DependentIsCollectedAfterTargetIsSetToNull()
[MethodImpl(MethodImplOptions.NoInlining)]
static DependentHandle Initialize(out object target, out WeakReference weakDependent)
{
target = new();
target = new object();
object dependent = new();
......@@ -268,7 +268,7 @@ public void SetTarget_NotAllocated_ThrowsInvalidOperationException()
Assert.Throws<InvalidOperationException>(() =>
{
DependentHandle handle = default;
handle.Target = new();
handle.Target = new object();
});
}
......@@ -281,7 +281,7 @@ public void SetTarget_NotNullObject_ThrowsInvalidOperationException()
try
{
handle.Target = new();
handle.Target = new object();
}
finally
{
......@@ -296,7 +296,7 @@ public void SetDependent_ThrowsInvalidOperationException()
Assert.Throws<InvalidOperationException>(() =>
{
DependentHandle handle = default;
handle.Dependent = new();
handle.Dependent = new object();
});
}
......
......@@ -285,7 +285,7 @@ void Initialize()
mapForCustomHeader = useProtectedMap ? protectedHeaders : unprotectedHeaders;
expectedProtectedHeaders = GetExpectedProtectedHeaders();
expectedUnprotectedHeaders = new();
expectedUnprotectedHeaders = new List<(CoseHeaderLabel, ReadOnlyMemory<byte>)>();
listForCustomHeader = useProtectedMap ? expectedProtectedHeaders : expectedUnprotectedHeaders;
}
}
......
......@@ -235,7 +235,7 @@ private static void AssertSign1Headers(CborReader reader, List<(CoseHeaderLabel,
private static ECParameters CreateECParameters(string curveFriendlyName, string base64UrlQx, string base64UrlQy, string base64UrlPrivateKey)
{
return new()
return new ECParameters()
{
Curve = ECCurve.CreateFromFriendlyName(curveFriendlyName),
Q = new ECPoint
......
......@@ -17,7 +17,7 @@ internal sealed class ConverterList : IList<JsonConverter>
public ConverterList(JsonSerializerOptions options)
{
_options = options;
_list = new();
_list = new List<JsonConverter>();
}
public ConverterList(JsonSerializerOptions options, ConverterList source)
......
......@@ -172,7 +172,7 @@ public static CachingContext GetOrCreate(JsonSerializerOptions options)
Debug.Assert(key._cachingContext == null);
ctx = new CachingContext(options);
bool success = cache.TryAdd(key, new(ctx));
bool success = cache.TryAdd(key, new WeakReference<CachingContext>(ctx));
Debug.Assert(success);
return ctx;
......
......@@ -679,7 +679,7 @@ public class CustomInt32ConverterSerializerContext : JsonSerializerContext
JsonTypeInfo<string> valueInfo = JsonMetadataServices.CreateValueInfo<string>(Options, JsonMetadataServices.StringConverter);
JsonCollectionInfoValues<Dictionary<int, string>> info = new()
{
ObjectCreator = () => new(),
ObjectCreator = () => new Dictionary<int, string>(),
KeyInfo = keyInfo,
ElementInfo = valueInfo,
};
......
......@@ -237,7 +237,7 @@ public async Task RuntimeConverterIsSupported_AsyncEnumerable()
Assert.Equal("Read", obj.Status);
ClassWithAsyncEnumerableConverter poco = new();
poco.MyAsyncEnumerable = new();
poco.MyAsyncEnumerable = new ClassThatImplementsIAsyncEnumerable();
Assert.Equal("Created", poco.MyAsyncEnumerable.Status);
serialized = await Serializer.SerializeWrapper(poco, options);
Assert.Equal(Json, serialized);
......@@ -252,7 +252,7 @@ public async Task CompileTimeConverterIsSupported_AsyncEnumerable()
const string Json = "{\"MyAsyncEnumerable\":[]}";
ClassWithAsyncEnumerableConverter obj = new();
obj.MyAsyncEnumerable = new();
obj.MyAsyncEnumerable = new ClassThatImplementsIAsyncEnumerable();
Assert.Equal("Created", obj.MyAsyncEnumerable.Status);
string serialized = await Serializer.SerializeWrapper(obj);
......
......@@ -390,7 +390,7 @@ private class DictionaryTestClass<TNested> : ITestObject where TNested : INested
void ITestObject.Initialize(INestedObject nested)
{
nested.Initialize();
A = new() { { "a", (TNested)nested }, { "b", (TNested)nested } };
A = new Dictionary<string, TNested>() { { "a", (TNested)nested }, { "b", (TNested)nested } };
}
void ITestObject.Verify()
......
......@@ -1767,7 +1767,7 @@ public static void AdaptableCustomConverter()
Converters = { new AdaptableInt32Converter() }
};
obj = new() { Prop = new List<int>() { 1 } };
obj = new PlainClassWithList() { Prop = new List<int>() { 1 } };
json = JsonSerializer.Serialize(obj, options);
Assert.Equal("{\"Prop\":[101]}", json);
......@@ -1775,13 +1775,13 @@ public static void AdaptableCustomConverter()
Assert.Equal(1, obj.Prop[0]);
// Then with strings
options = new()
options = new JsonSerializerOptions()
{
NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString,
Converters = { new AdaptableInt32Converter() }
};
obj = new() { Prop = new List<int>() { 1 } };
obj = new PlainClassWithList() { Prop = new List<int>() { 1 } };
json = JsonSerializer.Serialize(obj, options);
Assert.Equal("{\"Prop\":[\"101\"]}", json);
......
......@@ -132,7 +132,10 @@ public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo
else
{
// The set may match multiple characters. Search for that.
FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) };
FixedDistanceSets = new List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>()
{
(chars, set.CharClass, 0, set.CaseInsensitive)
};
FindMode = set.CaseInsensitive ?
FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive :
FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive;
......
......@@ -43,7 +43,7 @@ static bool TryAnalyze(RegexNode node, AnalysisResults results, bool isAtomicByA
case RegexNodeKind.Alternate:
case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M != node.N:
case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.M != node.N:
(results._mayBacktrack ??= new()).Add(node);
(results._mayBacktrack ??= new HashSet<RegexNode>()).Add(node);
break;
}
}
......@@ -120,7 +120,7 @@ static bool TryAnalyze(RegexNode node, AnalysisResults results, bool isAtomicByA
// will be visible from this node to it.
if (!isAtomicBySelf && (results._mayBacktrack?.Contains(child) == true))
{
(results._mayBacktrack ??= new()).Add(node);
(results._mayBacktrack ??= new HashSet<RegexNode>()).Add(node);
}
}
......
......@@ -263,7 +263,7 @@ bool TryGetIntersection(RegexNode node, [Diagnostics.CodeAnalysis.NotNullWhen(tr
return false;
}
conjuncts = new();
conjuncts = new List<RegexNode>();
conjuncts.Add(node.Child(0));
node = node.Child(1);
while (IsIntersect(node))
......@@ -293,7 +293,7 @@ private BDD CreateBDDFromSetString(bool ignoreCase, string set)
}
// Lazily-initialize the set cache on first use, since some expressions may not have character classes in them.
_setBddCache ??= new();
_setBddCache ??= new Dictionary<(bool IgnoreCase, string Set), BDD>();
// Try to get the cached BDD for the combined ignoreCase+set key.
// If one doesn't yet exist, compute and populate it.
......
......@@ -1053,8 +1053,8 @@ public PerThreadData(SymbolicRegexBuilder<TSetType> builder, int capsize)
// Only create data used for capturing mode if there are subcaptures
if (capsize > 1)
{
Current = new();
Next = new();
Current = new SparseIntMap<Registers>();
Next = new SparseIntMap<Registers>();
InitialRegisters = new Registers(new int[capsize], new int[capsize]);
}
}
......
......@@ -75,14 +75,14 @@ private static SymbolicRegexNode<S> Create(SymbolicRegexBuilder<S> builder, Symb
// Do not internalize top level Or-nodes or else NFA mode will become ineffective
if (kind == SymbolicRegexNodeKind.Or)
{
node = new(builder, kind, left, right, lower, upper, set, alts, info);
node = new SymbolicRegexNode<S>(builder, kind, left, right, lower, upper, set, alts, info);
return node;
}
left = left == null || left._kind != SymbolicRegexNodeKind.Or || left._isInternalizedUnion ? left : Internalize(left);
right = right == null || right._kind != SymbolicRegexNodeKind.Or || right._isInternalizedUnion ? right : Internalize(right);
node = new(builder, kind, left, right, lower, upper, set, alts, info);
node = new SymbolicRegexNode<S>(builder, kind, left, right, lower, upper, set, alts, info);
builder._nodeCache[key] = node;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册