开发者

Variable scope at the same source file in partial classes

Is there anyway to reuse a method/variable name in partial classes?

Something like internal which defines a variable scope at assembly level but this time at source file level. So we can use the same name in another code file and that variable is available to other members at the same code (*.cs) fil开发者_如何转开发e.


Is there anyway to reuse a method/variable name in partial classes?

No, because partial classes just mean that the actual class is split up amongst more than one file. At compile time they are combined into a single class, and all the same rules apply that normally does.

I don't know the specifics of what you are trying to do, but I suspect you could have two different classes and have one inherit from the other. Mark the methods etc. internal instead of private and then the subclass can see them like they were in the same class.

If you absolutely need to use the same variable name in the subclass, you can use the new key word: new string Foo = "this is a new string."; which will ignore the old Foo string in the base class and use the one you have just redeclared.

From the C# 4.0 Spec:

With the exception of partial methods (§10.2.7), the set of members of a type declared in multiple parts is simply the union of the set of members declared in each part. The bodies of all parts of the type declaration share the same declaration space (§3.3), and the scope of each member (§3.7) extends to the bodies of all the parts. The accessibility domain of any member always includes all the parts of the enclosing type; a private member declared in one part is freely accessible from another part. It is a compile-time error to declare the same member in more than one part of the type, unless that member is a type with the partial modifier.

partial class A
{
    int x;                      // Error, cannot declare x more than once
    partial class Inner     // Ok, Inner is a partial type
    {
        int y;
    }
}
partial class A
{
    int x;                      // Error, cannot declare x more than once
    partial class Inner     // Ok, Inner is a partial type
    {
        int z;
    }
}


Currently you don't have such option.

Partial classes are a syntactic sugar. All parts become the same class once compiled.


No, the least accessible modifier is private, and that will span the whole class.

You should really consider why you would even need that. I am not known for being uncreative (hope so), but I find it hard to picture a scenario, where this is really a requirement. One that isn't all weird, that is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜