Partial classes in different namespace are not being recognized correctly

断了今生、忘了曾经 提交于 2019-12-05 04:08:17

you cannot have a partial class in two namespaces. the compiler treats those as two different classes.

I have a partial that is split over two namespaces.

You can't. By being in different namespaces, they are different classes.

Consider that this is the reason namespaces exist - so you can have the same class name for different classes.

From the C# Language Specification (C# 4.0), §10.2, Partial types:

Each part of a partial type declaration must include a partial modifier. It must have the same name and be declared in the same namespace or type declaration as the other parts.

(emphasis mine)

So, by definition, what you are doing is not a partial type.

See Partial Class Definitions

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace.

This is due to the fact that partial types must be within the same namespace because each class has a fully quantified name which includes the namespace. A prime example of this is with Windows Forms Application the designer and the UI code are seperated using a partial class. It also prevents bad design in my opinion!

You can see this for yourself using simple reflection code (for fun mostly).

var namespaces = Assembly.GetExecutingAssembly().GetTypes()
                         .Select(t => t.Namespace)
                         .Distinct();

//Returns:
//  WindowsFormsApplication2
//  WindowsFormsApplication2.Properties

Namespaces provide logical seperation of Types. MyNamespace.One.Product and MyNamespace.Two.Product are two different types (if this were not the case, then there would be no point in having Namespaces in the first place!)

Because of using MyNamespace.One;,

In Main():

var item = new Product();

is the equivalent of:

var item = new MyNamespace.One.Product()

Change the namespace of the second Product type to MyNamespace.One

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!