2010-09-01 48 views
6

我正在使用實體框架與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並傳遞一個參考的基類,所以我可以訪問生成的屬性。或者,也許只是給他們一個特定的方式。但是,我不確定什麼是最好的解決方案。我正在尋找那些乾淨並且屬於良好實踐的社區理念。謝謝。

+0

順便說一句,你爲什麼要組的自定義屬性?有時你可以使用屬性來標記它們。 – 2010-09-01 03:55:54

回答

16

下面是使用另一種解決方案明確的接口:

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 
+2

使用顯式接口使代碼更具可讀性並具有良好的可擴展性。 – 2010-09-01 03:54:27

+0

+1對於顯式接口 – 2010-09-01 05:39:50

+0

是否有可能強制該接口是顯式的? – hunter 2010-09-01 12:48:22

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權的部分類,但我能理解爲什麼您可能要分離。

+0

我想這就是你在問題結束時所說的話。我想這個答案並不可怕,並得到你正在尋找的分離。 – hunter 2010-09-01 01:55:39

相關問題