Правильное форматирование операторов каскадного использованияC#

Место общения программистов C#
Ответить
Anonymous
 Правильное форматирование операторов каскадного использования

Сообщение Anonymous »

Я использую C# с Visual Studio. Параметры форматирования я указываю через EditorConfig. Мне удалось заставить работать почти все, но я не могу заставить его правильно форматировать каскадно с помощью операторов.
Ожидаемый результат форматирования:
public static void Main( string[] args )
{
using( var fileStream = new System.IO.FileStream( "file.txt", System.IO.FileMode.Open ) )
using( var streamReader = new System.IO.StreamReader( fileStream, System.Text.Encoding.UTF8 ) )
while( !streamReader.EndOfStream )
Console.WriteLine( streamReader.ReadLine() );
}

Фактический результат форматирования:
public static void Main( string[] args )
{
using( var fileStream = new System.IO.FileStream( "file.txt", System.IO.FileMode.Open ) )
using( var streamReader = new System.IO.StreamReader( fileStream, System.Text.Encoding.UTF8 ) )
while( !streamReader.EndOfStream )
Console.WriteLine( streamReader.ReadLine() );
}

Примечание: эта проблема сохраняется, даже если я отключу ReSharper.
Вопрос в том, какие магические заклинания мне нужно поместить в файл .editorconfig чтобы достичь «ожидаемого» результата форматирования вместо «фактического» результата форматирования?
Я знаю, что этот особый стиль отступов каскадных операторов using очень популярен в мир дотнета; тем не менее, это особый случай, и я бы предпочел обойтись без особых случаев.
Вся суть .editorconfig состоит в том, чтобы предоставить разработчикам свободу выбора, так где же моя свобода выбора форматирования моего каскадного использования< Операторы /code> не должны быть особыми?
Все те программисты C#, которым нравится форматирование особых случаев каскадного использования операторы должны быть рады знайте, что их извращение может быть выполнено с помощью конструкции, представленной в C# 8, называемой «использование объявлений», которая обеспечивает тот же эффект отступа, не требуя какого-либо форматирования в особом случае.
Для справки, вот весь мой файл .editorconfig:
# PEARL: Visual Studio offers no special support for the .editorconfig syntax!
# The "EditorConfig Language Service" extension has not been updated since 2021 and is incompatible with VS2022.
# PEARL: The rule for spaces between parentheses in method calls is also applied to compile-time operators
# such as nameof and typeof even though they are definitely not method calls!

root = true

[*]

indent_style = tab
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = off
indent_size = 4
tab_width = 4

[*.md]

[*.xaml]

[*.cs]

###############################################################################

# PEARL: All spell-checking-related functionality is undocumented.
# There exist a few blog posts about it, explaining it in wishy-washy, hand-wavy terms,
# but there exists no official reference for it.
# PEARL: The spell-checking dictionary for "en-us" apparently includes the word "Covfefe".
# PEARL: Microsoft uses the term "exclusion" for the custom spell-checking dictionary.
# They choose to think of it in terms of exclusion, which is entirely unwarranted.
# As far as we are concerned, this file has nothing to do with any form of exclusion;
# it is just our custom spell-checking dictionary.

# This apparently selects basic spell-checking dictionaries for certain languages.
# We want en-us only, because "initialise" instead of "initialize" makes me angry.
spelling_languages = en-us

# Specifies where to spell check. Possible values seem to be: strings, identifiers, comments. We want everything.
spelling_checkable_types = strings, identifiers, comments

# Spelling error severity. Possible values seem to be: error, warning, information, hint.
spelling_error_severity = information

# Custom spell-checking file to use. (Either absolute or relative to the root of the solution.)
spelling_exclusion_path = ./exclusion.dic

# The "default exclusion dictionary" for C# contains a ton of nonsense which we definitely do not want.
spelling_use_default_exclusion_dictionary = false
# NOTE: on my machine, the "default exclusion dictionary" for C# is C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Editor\SpellChecker\ExclusionDictionaries\csharp.dic

###############################################################################
# Severities:
# error - Violations appear as build errors and cause builds to fail.
# warning - Violations appear as build warnings but do not cause builds to fail (unless you have an option set to treat warnings as errors).
# suggestion - Violations appear as build messages and as suggestions in the Visual Studio IDE.
# silent - Violations aren't visible to the user.
# none - Rule is suppressed completely.
# default - The default severity of the rule is used. The default severities for each .NET release are listed in the roslyn-analyzers repo. In that table, "Disabled" corresponds to none, "Hidden" corresponds to silent, and "Info" corresponds to suggestion.

dotnet_diagnostic.severity = warning

# IDE0047: Remove unnecessary parentheses
dotnet_diagnostic.IDE0047.severity = silent

# IDE0063: Use simple 'using' statement
dotnet_diagnostic.IDE0063.severity = silent

# IDE0017: Simplify object initialization
dotnet_diagnostic.IDE0017.severity = silent

# IDE0058: Expression value is never used
dotnet_diagnostic.IDE0058.severity = silent

# CA1051: Do not declare visible instance fields
# Visible instance fields are absolutely fine if immutable.
dotnet_diagnostic.CA1051.severity = none

###############################################################################

dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false
file_header_template = unset

# These control the use of `.this`
dotnet_style_qualification_for_field = false
dotnet_style_qualification_for_property = false
dotnet_style_qualification_for_method = false
dotnet_style_qualification_for_event = false

dotnet_style_predefined_type_for_locals_parameters_members = true
dotnet_style_predefined_type_for_member_access = true

# IDE0040 "Accessibility modifiers required"
# Option values:
# - always
# - for_non_interface_members
# - never
# - omit_if_default
# PEARL: It is entirely unclear what the difference is between "never" and "omit_if_default".
# Observations show that "omit_if_default" is completely useless, and "never" must be used instead.
# PEARL: "warning" must be explicitly specified or else this has no effect.
dotnet_style_require_accessibility_modifiers = never:warning

# IDE0047 "Remove unnecessary parentheses"
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary
dotnet_style_parentheses_in_other_operators = never_if_unnecessary

dotnet_style_coalesce_expression = true
dotnet_style_collection_initializer = true:silent
dotnet_style_explicit_tuple_names = true:silent
dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true
dotnet_style_object_initializer = true:silent
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true
dotnet_style_prefer_compound_assignment = true ;?
dotnet_style_prefer_conditional_expression_over_assignment = true
dotnet_style_prefer_conditional_expression_over_return = false ; # IDE0046 "Convert to conditional expression"
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_inferred_anonymous_type_member_names = true:silent
dotnet_style_prefer_inferred_tuple_names = true:silent
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
dotnet_style_prefer_simplified_boolean_expressions = true
dotnet_style_prefer_simplified_interpolation = true

dotnet_style_readonly_field = true

###############################################################################

# Available values for capitalization:
# pascal_case
# camel_case
# first_word_upper
# all_upper
# all_lower

# Available values for applicable_kinds:
# property
# method
# field
# event
# delegate

dotnet_naming_style.pascal_case_style.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =

dotnet_naming_style.camel_case_style.capitalization = camel_case
dotnet_naming_style.camel_case.required_prefix =
dotnet_naming_style.camel_case.required_suffix =
dotnet_naming_style.camel_case.word_separator =

dotnet_naming_rule.camel_case_private_members.severity = suggestion
dotnet_naming_rule.camel_case_private_members.symbols = private_members
dotnet_naming_rule.camel_case_private_members.style = camel_case_style
dotnet_naming_symbols.private_members.applicable_kinds = property, method, field, event
dotnet_naming_symbols.private_members.applicable_accessibilities = private
dotnet_naming_symbols.private_members.required_modifiers = *

dotnet_naming_rule.pascal_case_non_private_members.severity = suggestion
dotnet_naming_rule.pascal_case_non_private_members.symbols = private_members
dotnet_naming_rule.pascal_case_non_private_members.style = camel_case_style
dotnet_naming_symbols.non_private_members.applicable_kinds = property, method, field, event
dotnet_naming_symbols.non_private_members.applicable_accessibilities = public, protected, internal
dotnet_naming_symbols.non_private_members.required_modifiers = *

dotnet_style_readonly_field = true
dotnet_code_quality_unused_parameters = all
dotnet_remove_unnecessary_suppression_exclusions = none
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = true

###############################################################################

csharp_style_var_elsewhere = false
csharp_style_var_for_built_in_types = false
csharp_style_var_when_type_is_apparent = true

# IDE0022: Use expression body for method
csharp_style_expression_bodied_accessors = when_on_single_line
csharp_style_expression_bodied_constructors = false
csharp_style_expression_bodied_indexers = when_on_single_line
csharp_style_expression_bodied_lambdas = true
csharp_style_expression_bodied_local_functions = when_on_single_line
csharp_style_expression_bodied_methods = when_on_single_line
csharp_style_expression_bodied_operators = when_on_single_line
csharp_style_expression_bodied_properties = when_on_single_line

csharp_style_pattern_matching_over_is_with_cast_check = true
csharp_style_pattern_matching_over_as_with_null_check = true
csharp_style_prefer_extended_property_pattern = true
csharp_style_prefer_not_pattern = true
csharp_style_prefer_pattern_matching = true
csharp_style_prefer_switch_expression = true

csharp_style_conditional_delegate_call = true

csharp_prefer_static_local_function = true
csharp_preferred_modifier_order = public, private, protected, internal, file, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, required, volatile, async
csharp_style_prefer_readonly_struct = true
csharp_style_prefer_readonly_struct_member = true

csharp_prefer_braces = false:warning
csharp_prefer_simple_using_statement = false
csharp_style_namespace_declarations = file_scoped
csharp_style_prefer_method_group_conversion = true
csharp_style_prefer_top_level_statements = false

csharp_prefer_simple_default_expression = true
csharp_style_deconstructed_variable_declaration = true
csharp_style_implicit_object_creation_when_type_is_apparent = true
csharp_style_inlined_variable_declaration = true
csharp_style_prefer_index_operator = true
csharp_style_prefer_local_over_anonymous_function = true:silent
csharp_style_prefer_null_check_over_type_check = true
csharp_style_prefer_range_operator = true
csharp_style_prefer_tuple_swap = true
csharp_style_prefer_utf8_string_literals = true
csharp_style_throw_expression = true
csharp_style_unused_value_assignment_preference = discard_variable
csharp_style_unused_value_expression_statement_preference = discard_variable

csharp_using_directive_placement = inside_namespace

csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = false
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = false
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
csharp_style_allow_embedded_statements_on_same_line_experimental = false

###############################################################################

csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true

csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = false
csharp_indent_labels = flush_left
csharp_indent_switch_labels = true

csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = false
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = true
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = true
csharp_space_between_parentheses = control_flow_statements ; possible values: control_flow_statements, type_casts, expressions
csharp_space_between_square_brackets = false

csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false

# PEARL: This is not about spaces, it is about ***extra*** spaces (i.e. two or more spaces.)
# Essentially, it can be used to allow tabular code formatting. Which we don't.
csharp_space_around_declaration_statements = false


Подробнее здесь: https://stackoverflow.com/questions/767 ... statements
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»