Pergunta

So i have 2 distinct methods.

one is a normal method

void DoSomething(delegate x)
{
     foreach(......)
     { x(); }
}

the other is a partial but unimplemented one

partial void DoWorkInForEach();

when i call my first method like this

DoSomething(DoWorkInForEach);

what will happen, will the delegate parameter be null, will my entire method call be deleted?

Foi útil?

Solução

From the language specification:

10.2.7 Partial methods

[...]

If a defining declaration but not an implementing declaration is given for a partial method M, the following restrictions apply:

It is a compile-time error to create a delegate to method (§7.6.10.5).

• It is a compile-time error to refer to M inside an anonymous function that is converted to an expression tree type (§6.5.2).

• Expressions occurring as part of an invocation of M do not affect the definite assignment state (§5.3), which can potentially lead to compile-time errors.

• M cannot be the entry point for an application (§3.1).

If required, you can use a lambda here instead of a method-group, which would essentially give you a no-op delegate:

DoSomething(() => DoWorkInForEach());

Outras dicas

Theory

According to the MSDN:

You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.

And also C# Language Specification:

If a defining declaration but not an implementing declaration is given for a partial method M, the following restrictions apply: It is a compile-time error to create a delegate to method (§7.6.10.5).


Example

The below is correct:

partial class Foo
{
    partial void Method();

    Foo()
    {
        Action action = new Action(Method);
    }
}

partial class Foo
{
    partial void Method()
    {
        // ...
    }
}

And the following will throw a compilation error:

Cannot create delegate from method 'Test.Foo.Method()' because it is a partial method without an implementing declaration

partial class Foo
{
    partial void Method();

    Foo()
    {
        Action action = new Action(Method); // Compilation error
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top