【问题标题】:How to create a group of methods/properties within a class?如何在一个类中创建一组方法/属性?
【发布时间】:2011-04-06 13:55:33
【问题描述】:

我正在使用带有 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 的分部类中创建另一个类,并将引用传递给基类,以便我可以访问生成的属性。或者也许只是以一种特定的方式命名它们。但是,我不确定什么是最好的解决方案。我正在寻找干净且符合良好实践的社区想法。谢谢。

【问题讨论】:

  • 顺便说一句,你为什么要对这些自定义属性进行分组?有时你可以使用属性来标记它们。

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


【解决方案1】:

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

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 使用显式接口使代码更具可读性和良好的可扩展性。
  • 是否可以强制该接口显式?
  • 当您具有默认可访问性并将接口名称添加到属性/方法名称之前,该接口将显式实现。 “显性”在于实现,而不在于接口本身。
  • 请注意此类类不会在 MVC3 中绑定
【解决方案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 类上,但我明白你为什么可能想要分离。

【讨论】:

  • 我认为这就是您在问题结束时所说的。我想这个答案并不可怕,并且得到了你正在寻找的分离。
猜你喜欢
  • 2010-10-15
  • 2020-07-09
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 2021-12-17
  • 2022-01-01
相关资源
最近更新 更多