How to create a group of methods/properties within a class?
I am using entity framework with a web service and I have entity partial class objects that were generated automatically by the web service.
I would like to extend these classes, but I would like to group them in the generated class in a way similar to the way a namespace would (except inside a class).
Here is my generated class:
public partial class Employee : Entity
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And I want to add some new properties, functions, etc similar to:
pu开发者_JAVA技巧blic partial class Employee : Entity
{
public string FullName {
get { return this.FirstName + " " + this.LastName; }
}
}
However, I would like to group any additional properties together so I have a little more visible separation from the generated methods. I would like to be able to call something like:
myEmployee.CustomMethods.FullName
I could create another class within the partial class called CustomMethods and pass a reference to the base class so I can access the generated properties. Or maybe just name them a particular way. But, I am not sure what is the best solution. I am looking for community ideas that are clean and fall under good practice. Thanks.
Here is another solution using explicit interfaces:
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; }
}
}
Usage:
string fullName;
fullName = employee.FullName; //Compiler error
fullName = employee.CustomMethods.FullName; //OK
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;
}
}
}
typically I would put Properties like FullName
right on the Partial class but I can see why you might want separation.
精彩评论