简体   繁体   中英

Erroneous code, when overriding async method. Can this behavior be turned off?

Let's consider this class:

public class A
{
    public virtual async Task FooAsync()
    {
        await Task.Delay(3000);
    }
}

If you'll try to override FooAsync by typing "override" + selecting FooAsync from list, VS 2013 code editor will generate this code:

    public override async Task FooAsync()
    {
        return base.FooAsync();
    }

which, obviously, won't compile, until you'll change return to await .

I know, that async is an implementation detail, and it could be changed in derived type, but this isn't a cause to generated code, which doesn't compile initially.

Can this behavior be turned off (eg, using some VS settings)?

I don't believe that there's a way to change this behaviour. The code to be added comes from a snippet, found (on my machine) under c:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\vc#\\Snippets\\1033\\Refactoring\\MethodOverrideStub.snippet . The snippet is:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Method Override Stub</Title>
            <Description>Snippet for overriding a method</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Refactoring</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal Editable="true">
                    <ID>signature</ID>
                    <Default>signature</Default>
                </Literal>
                <Literal>
                    <ID>CallBase</ID>
                    <Function>CallBase(method)</Function>
                </Literal>
            </Declarations>
            <Code Language="csharp">
                <![CDATA[$signature$
{
    $end$ $CallBase$
}]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Unfortunately, as you can hopefully see, the actual "interesting" bits that determine the method signature and invoke the base class method are not part of the snippet - they're calculated by code instead.

Visual Studio 2015 (looking at RC / 14.0.22823.1 D14REL) appears to resolve the issue, but in the opposite way to how you've asked - it avoids copying async into the signature, which is more correct since async really shouldn't be considered as part of a method signature, as I think you yourself allude to in your question; It's an implementation detail and changing how the method is implemented shouldn't affect the signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM