Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - Splitting/Combining Partial Methods

I understand partial methods can be used to split the definition of a method across multiple files. I'm curious though if it's permissible to have each definition of a method across multiple files contain code?

For example, say I have a method private partial void Foo(). Let's say I've got it defined in file A and file B. Can both instances have code contained in the method, or just one or the other? I guess I'd be surprised if this were permitted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is really a comment to @Bruno's answer and may not be completely relevant to the question:

The decision to not allow partial methods to have multiple implementations is an arbitrary decision made in the design of the language. Your argument is a good reason why you might decide against allowing such a thing in your language but there isn't really a technical limitation. You can very easily decide to allow multiple implementation and let the compiler decide the order of execution of implementations. Actually, C# specification already has cases with undefined order for partial classes:

// A.cs:
partial class Program {
    static int x = y + 42;
    static void Main() {
       System.Console.WriteLine("x: {0}; y: {1}", x, y);
    }
}

// B.cs:
partial class Program {
    static int y = x + 42;
}

This is valid C# according to the C# Specification v3.0 but the output can be:

x: 42; y: 84

or

x: 84; y: 42

and the compiler is allowed to generate either of them. It doesn't even generate a warning.

The C# language requires a partial method to to have a void return type. The partial method signature can be defined at most once. Likewise, the implementation should be defined at most once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...