部分类中同一源文件的变量范围
无论如何,是否可以在部分类中重用方法/变量名称?
像 internal
这样的东西在程序集级别定义了变量范围,但这次是在源文件级别。因此,我们可以在另一个代码文件中使用相同的名称,并且该变量可供同一代码 (*.cs) 文件中的其他成员使用。
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) file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,因为部分类只是意味着实际的类被分成多个文件。在编译时,它们被组合成一个类,并且应用所有与通常相同的规则。
我不知道你想要做什么的具体细节,但我怀疑你可能有两个不同的类,并且一个类继承另一个类。将方法等标记为内部而不是私有,然后子类可以看到它们,就像它们在同一个类中一样。
如果你绝对需要在子类中使用相同的变量名,你可以使用 new 关键字:
new string Foo = "this is a new string.";
这将忽略旧的 Foo 字符串基类并使用您刚刚重新声明的基类。来自 C# 4.0 规范:
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:
目前你没有这样的选择。
部分类是语法糖。编译后,所有部分都成为同一类。
Currently you don't have such option.
Partial classes are a syntactic sugar. All parts become the same class once compiled.
不,最难访问的修饰符是 private,并且它将跨越整个类。
你应该真正考虑一下为什么你需要它。我并不以缺乏创造力而闻名(希望如此),但我发现很难想象一个场景,其中这确实是一个要求。这并不奇怪。
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.