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

时间:2010-09-01 01:32:26

标签: c# wpf silverlight web-services entity-framework

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

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

这是我生成的课程:

public partial class Employee : Entity
{
   public int ID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

我想添加一些类似于:

的新属性,功能等
public partial class Employee : Entity
{
   public string FullName {
      get { return this.FirstName + " " + this.LastName; }
   }
}

但是,我想将所有其他属性组合在一起,以便与生成的方法有一些更明显的分离。我希望能够打电话:

myEmployee.CustomMethods.FullName

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

2 个答案:

答案 0 :(得分: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; }
    }
}

用法:

string fullName;
fullName = employee.FullName; //Compiler error    
fullName = employee.CustomMethods.FullName; //OK

答案 1 :(得分:2)

public class CustomMethods
{
    Employee _employee;
    public CustomMethods(Employee employee)
    {
        _employee = employee;
    }

    public string FullName 
    {
        get 
        {
            return string.Format("{0} {1}", 
                _employee.FirstName, _employee.LastName); 
        }
    }
}

public partial class Employee : Entity
{
    CustomMethods _customMethods;
    public CustomMethods CustomMethods
    {
        get 
        {
            if (_customMethods == null)
                _customMethods = new CustomMethods(this);
            return _customMethods;
        }
    }
}

通常我会将像FullName这样的属性放在Partial类上,但我可以看到为什么你可能需要分离。

相关问题