C#分部类 [英] C# Partial Classes

查看:172
本文介绍了C#分部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有与大多使用同一类的多个项目的解决方案。其结果是,它在我看来,这将是一个好主意,加入溶液中含有这些类,而不是重复在每个项目中的类类库。

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 containing these classes in the solution instead of repeating the class in each project.

然而,一个项目我也需要一些额外的属性,有些是特定于该项目,将无法在其他地方使用的类。因此,我认为我应该使用局部类添加这些属性。所以,我做了这样的事情:

However, one project I have requires a few additional properties to some of the classes that are specific to that project and will not be used anywhere else. As a result, I thought that I should use partial classes to add these properties. So I have done something like this:

在类库:

namespace MyClassLibrary
{
    public partial class Book
    {
        public string Title { get; set; }
        public string AuthorLast { get; set; }
        public string AuthorFirst { get; set; }
        public string Publisher { get; set; }
        public string Edition { get; set; }
        public string ISBN10 { get; set; }
        public string ISBN13 { get; set; }
    }
}

在项目(MyProject的):

In the project (MyProject):

namespace MyClassLibrary
{
    public partial class Book
    {
        public string AdditionalProperty { get; set; }
    }
}



我在MyProject的参考MyClassLibrary(一个C#窗口表格应用程序),但是当我尝试使用这个类的代码隐藏,因为我收到以下错误的形式:

I have referenced MyClassLibrary in MyProject (a C# windows form app), however when I try to use this class in the codebehind for the form I receive the following error:

类MyClassLibrary.Book

class MyClassLibrary.Book

警告:类型
'MyClassLibrary.Book在C:...
(项目)与进口$ b $冲突b。在':...
(类库DLL)C''MyClassLibrary.Book。使用中定义的类型
'C:...(项目)。

Warning: The type 'MyClassLibrary.Book' in 'C:... (Project)' conflicts with the imported type 'MyClassLibrary.Book' in 'C:... (Class Library DLL)'. Using the type defined in 'C:...(project)'.

任何想法,我做错了或者,如果我的整个做法是坏的,我应该做点别的?

Any idea what I am doing wrong or if my whole approach is bad and I should be doing something else?

推荐答案

局部模板不是为跨越组件。如果您需要添加到您的类更具体的使用方式,你应该创建一个派生类:

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;}
}

在您的项目要求更具体的类型MyFoo的,利用MySpecificFoo来代替。由于它继承MyFoo /导出,它将拥有所有的属性和MyFoo的功能,与其他属性为好。这是 多态性 的一部分正是OOP的真正的力量所在。

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.

这篇关于C#分部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆