如何在类中创建一组方法/属性?

Ada*_*dam 7 c# silverlight wpf entity-framework web-services

我正在使用带有Web服务的实体框架,并且我有由Web服务自动生成的实体部分类对象.

我想扩展这些类,但我想以类似于命名空间的方式(在类中除外)的方式将它们分组在生成的类中.

这是我生成的类:

public partial class Employee : Entity
{
   public int ID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想添加一些新的属性,功能等类似于:

public partial class Employee : Entity
{
   public string FullName {
      get { return this.FirstName + " " + this.LastName; }
   }
}
Run Code Online (Sandbox Code Playgroud)

但是,我想将任何其他属性组合在一起,这样我与生成的方法有一些更明显的分离.我想能够打电话给:

myEmployee.CustomMethods.FullName
Run Code Online (Sandbox Code Playgroud)

我可以在名为CustomMethods的分部类中创建另一个类,并将引用传递给基类,以便我可以访问生成的属性.或者也许只是以特定方式命名它们.但是,我不确定什么是最好的解决方案.我正在寻找干净且属于良好实践的社区理念.谢谢.

Igo*_*aka 17

这是使用显式接口的另一种解决方案

public interface ICustomMethods {
    string FullName {get;}
}

public partial class Employee: Entity, ICustomMethods {
    public ICustomMethods CustomMethods {
       get {return (ICustomMethods)this;}
    }
    //explicitly implemented
    string ICustomMethods.FullName {
       get { return this.FirstName + " " + this.LastName; }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

string fullName;
fullName = employee.FullName; //Compiler error    
fullName = employee.CustomMethods.FullName; //OK
Run Code Online (Sandbox Code Playgroud)

  • 使用显式接口的+1使代码更具可读性和良好的可扩展性. (2认同)