[英]Can partial class access static methods in C#?
The tutorial application, MusicStore -MVC3 (92 PageNo) , created a POCO class like: 教程应用程序MusicStore -MVC3(92 PageNo)创建了一个POCO类,例如:
public partial class ShoppingCart
{
MusicStoreEntities storeDB = new MusicStoreEntities();
public static ShoppingCart GetCart(HttpContextBase context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
}
How can we access static method in partial classes? 我们如何在局部类中访问静态方法? In my opinion, we cannot access static methods in a partial class.
我认为,我们不能在局部类中访问静态方法。 The
partial
attribute means other parts of the class will be included in the namespace. partial
属性表示该类的其他部分将包含在名称空间中。 In this scenario, I do not know where this other partial class is implemented. 在这种情况下,我不知道其他部分类在哪里实现。
My questions about this static method are: 我对此静态方法的疑问是:
Updated: There is no other ShoppingCart
class in the models
directory. 已更新:
models
目录中没有其他ShoppingCart
类。 Does anyone know where that partial implementation would be? 有谁知道部分实现将在哪里?
A partial
class in C# can definitely access static
methods. C#中的
partial
类绝对可以访问static
方法。 The partial
attribute simply says a class can (not must ) be defined accross multiple files and otherwise doesn't affect member lookup. 的
partial
属性只是说一个类可以 (未必须 )被翻过多个文件中定义的和以其他方式不影响成员查找。
EDIT Responding to comment in question 编辑回应有问题的评论
A possible explanation for why you can't find the other implementation of ShoppingCart
is it may not exist. 为什么找不到
ShoppingCart
的其他实现的一个可能解释是它可能不存在。 A partial
class is not required to have multiple definitions. 一个
partial
类不要求有多种定义。 The partial
only means there may be other parts of the definition. 仅
partial
表示定义中可能存在其他部分。
Yes, you can access static methods in partial classes. 是的,您可以在部分类中访问静态方法。
Partial classes are just a way of representing a regular class in multiple source files, often with some of those source files controlled (or generated) by tools. 局部类只是在多个源文件中表示常规类的一种方式,通常这些源文件中的某些受工具控制(或生成)。
You can call ShoppingCart.GetCart(context)
anywhere - it's a normal public static method. 您可以在任何地方调用
ShoppingCart.GetCart(context)
-这是一种常规的公共静态方法。
It's still not really clear what your second question means, but there doesn't have to be another part at all. 仍然不清楚您的第二个问题是什么意思,但是根本没有必要再讨论其他问题。 It's fine (though unusual) to have a partial class which is only declared in a single file.
拥有只在单个文件中声明的局部类是很好的(尽管很不寻常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.