public sealed class Person
{
public int Id { get; init; }
public int Name { get; set; }
public int Surname { get; set; }
public Person Set() => this;
}
Before, in F# 6, the following code would’ve compiled and mutated the property Id of the Person:
let person = Person(Id = 42, Name = "John", Surname = "Doe")
person.Id <- 123
person.set_Id(123)
person.Set(Id=123)
по AOT для F# "еще работают". Видать слишком много метапрограммистской магии.
Pattern matching is one of the ongoing stories in C# that we just keep filling out. Pattern matching was introduced in C# 7 and since then it has grown to become one of the most important and powerful control structures in the language.
C# 11 adds list patterns to the story. With list patterns you can apply patterns recursively to the individual elements of list-like input – or to a range of them. Let’s jump right in with the generic algorithm from above, rewritten as a recursive method using list patterns:
T AddAll<T>(params T[] elements) where T : IMonoid<T> =>
elements switch
{
[] => T.Zero,
[var first, ..var rest] => first + AddAll<T>(rest),
};
There’s a lot going on, but at the center is a switch expression with two cases. One case returns zero for an empty list [], where Zero is defined by the interface. The other case extracts the first element into first with the var first pattern, and the remainder is extracted into rest using the .. to slice out all the remaining elements into the var rest pattern.
S>Сопоставление шаблонов — это одна из постоянных историй в C #, которую мы просто продолжаем заполнять. Сопоставление с образцом было введено в C # 7, и с тех пор оно превратилось в одну из самых важных и мощных управляющих структур в языке.
S>C # 11 добавляет шаблоны списков в историю. С помощью шаблонов списков вы можете рекурсивно применять шаблоны к отдельным элементам ввода, подобного списку, или к их диапазону. Давайте сразу перейдем к описанному выше общему алгоритму, переписанному как рекурсивный метод с использованием шаблонов списков:
S>
S>T AddAll<T>(params T[] elements) where T : IMonoid<T> =>
S> elements switch
S>{
S> [] => T.Zero,
S> [var first, ..var rest] => first + AddAll<T>(rest),
S>};
S>
S>Там много чего происходит, но в центре находится выражение switch с двумя падежами. Один случай возвращает ноль для пустого списка[], где Zeroопределяется интерфейсом. В другом случае первый элемент извлекается firstс var firstпомощью шаблона, а оставшаяся часть извлекается с restпомощью.., чтобы вырезать все оставшиеся элементы в var restшаблоне.
Raw string literals
A lot of what gets put in string literals is “code” of some sort – not just program text, but also JSON and XML data, HTML, regular expressions, SQL queries, etc. It’s really unhelpful when many of the special characters that show up in such text have special meaning in C# string literals! Noteworthy examples include \ and ", joined in interpolated strings by { and }. Having to escape all of those is a real bummer, and an ongoing source of pain an bugs.
Why not have a form of string literals that has no escape characters at all? That’s what raw string literals are. Everything is content!
A raw string literal is delimited by at least three double-quotes:
var raw1 = """This\is\all "content"!""";
Console.WriteLine(raw1);
This prints:
This\is\all "content"!
If you need three or more "s to be part of your content, you just use more "s on the outside. The beginning and end just have to match:
var raw2 = """""I can do ", "", """ or even """" double quotes!""""";
This makes it really easy to paste in, maintain and read at a glance what the literal contains.
Multi-line raw string literals can also truncate leading white space: The position of the end quote determines where white space starts to be included in the output:
var raw3 = """
<element attr="content">
<body>
This line is indented by 4 spaces.
</body>
</element>
""";
// ^white space left of here is removed
Since there are four spaces to the left of the end quote, four spaces will be removed from the beginning of every line of content, yielding this output:
<element attr="content">
<body>
This line is indented by 4 spaces.
</body>
</element>
There’s much more to raw string literals than this – for instance they support interpolation! Read more about raw string literals in the docs.
Начиная с C# 11, можно использовать необработанные строковые литералы для упрощения создания строк, которые являются многостроочными, или использовать любые символы, требующие escape-последовательностей. Необработанные строковые литералы удаляют необходимость использования escape-последовательностей. Вы можете написать строку, включая форматирование пробелов, как она будет отображаться в выходных данных. Необработанный строковый литерал:
Начинается и заканчивается последовательность не менее трех символов двойной кавычки ("""). Для поддержки строковых литералов, содержащих три повторяющихся символа кавычки, разрешено начинать и заканчивать последовательность более трех последовательных символов.
Однострочные необработанные строковые литералы требуют символов открывающей и закрывающей кавычки в одной строке.
Многострочный необработанные строковые литералы требуют как открывающих, так и закрывающих символов кавычки в собственной строке.
В многострочных строковых литералах все пробелы слева от закрывающих кавычек удаляются.
Спешу предостеречь от поспешного перехода.
К сожалению есть достаточно мелких недоработок, которые могут подпортить вам жизнь в самый неподходящий момент.
Например сломался парсер JSON на некоторых документах
Здравствуйте, hi_octane, Вы писали:
_NN>>Например сломался парсер JSON на некоторых документах _>А сломался парсер на генераторах, или тот который на рефлексии?
Пять из этих шести ссылок относятся к старым тикетам (.NET 5 и .NET 6, 2021 год), и не связаны с регрессией в .NET 7.
Не очень соответствует заявлению: НС>Спешу предостеречь от поспешного перехода. НС>Например сломался парсер JSON на некоторых документах
Здравствуйте, Qbit86, Вы писали:
Q>Здравствуйте, _NN_, Вы писали:
_NN>>Например сломался парсер JSON на некоторых документах
Q>А можно ссылку на issue?
К сожалению, ссылки пока нет.
Баг открыт во внутренней системе.
Здравствуйте, Qbit86, Вы писали:
Q>Здравствуйте, _NN_, Вы писали:
_NN>>Например сломался парсер JSON на некоторых документах
Q>А можно ссылку на issue?