What is a partial class?

2019-03-27 12:08发布

What is and how can it be used in C#.
Can you use the same concept in Python/Perl?

8条回答
爷的心禁止访问
2楼-- · 2019-03-27 12:39

A partial type (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.

The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.

I've no idea whether Python/Perl have the same capabilities, I'm afraid.

查看更多
趁早两清
3楼-- · 2019-03-27 12:41

Python also has meta classes but that is more like a template class than a partial class. A good example of meta class usage is the Django ORM. All of your table models inherit from a base model class which also gets functionality included from a meta class. It is a pretty cool concept that enables an active record like pattern (is it full active record?).

查看更多
老娘就宠你
4楼-- · 2019-03-27 12:50

Partial class comes handy when you have auto-generated code by some tool. Refer question Project structure for Schema First Service Development using WCF for an example.

You can put your logic in the partial class. Even if the auto-generated file is destroyed and recreated, your logic will persist in the partial class.

查看更多
Root(大扎)
5楼-- · 2019-03-27 12:52

A partial class is simply a class that's contained in more than one file. Sometimes it's so that one part can be machine-generated, and another part user-edited.

I use them in C# when I'm making a class that's getting a bit too large. I'll put the accessors and constructors in one file, and all of the interesting methods in a different file.

In Perl, you'd simply have two (or more) files that each declare themselves to be in a package:

(main program)

    use MyClass;

(in MyClass.pm)

    use MyClassOtherStuff;
    package MyClass;
    # [..class code here...]

(in MyClassOtherStuff.pm)

    package MyClass;
    # [...rest of code here...]
查看更多
够拽才男人
6楼-- · 2019-03-27 12:55

The concept of partial types have already been explained.

This can be done in python. As an example, do the following in a python shell.

class A(object):
    pass

obj = A()

def _some_method(self):
    print self.__class__
A.identify = _some_method

obj.identify()
查看更多
We Are One
7楼-- · 2019-03-27 12:55

A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..)

No you don't have the same syntactical element in Python.

查看更多
登录 后发表回答