C# Partial Classes

后端 未结 5 1146
盖世英雄少女心
盖世英雄少女心 2021-01-04 01:04

I currently have a solution with multiple projects that mostly use the same classes. As a result, it appeared to me that it would be a good idea to add a class library cont

相关标签:
5条回答
  • 2021-01-04 01:30

    all wrong. You should consider partial methods instead. Look 'em up. They're exactly what you asked for.

    0 讨论(0)
  • 2021-01-04 01:33

    I think this is more along the lines of what you're trying to achieve.

    Put all of your common classes into a class library project and compile it to a DLL.

    You can then reference that DLL in external projects. Anytime you need to add a property to it for the external project you can then inherit the class and add the property there.

    0 讨论(0)
  • 2021-01-04 01:34

    In short, you can't use partial classes across projects. All the source must be compiled at the same time, and that's done per project.

    Here's a full discussion on SO about this: Should you use a partial class across projects?

    0 讨论(0)
  • 2021-01-04 01:35

    For what you're trying to do, you should instead try to use base classes and inheritance. Or even better object composition.

    0 讨论(0)
  • 2021-01-04 01:45

    Partials are not for spanning assemblies. If you need to add to your class for a more specific type of usage, you should create a derived class:

    public class MyFoo
    {
        public string BasicProperty {get;set;}
    }
    
    public class MySpecificFoo : MyFoo
    {
        public string AnotherProperty {get;set;}
    }
    

    In your project requiring the more specific type of MyFoo, utilize MySpecificFoo instead. Since it inherits/derives from MyFoo, it will have all of the properties and functionality of MyFoo, with the additional properties as well. This is part of Polymorphism, which is where real power of OOP lies.

    0 讨论(0)
提交回复
热议问题