C# 如何在类中创建一组方法/属性?
我将实体框架与web服务一起使用,并且我拥有由web服务自动生成的实体部分类对象 我想扩展这些类,但我想在生成的类中以类似于命名空间的方式对它们进行分组(类内部除外) 这是我生成的类:C# 如何在类中创建一组方法/属性?,c#,wpf,silverlight,web-services,entity-framework,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 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的类,并传递对基类的引用,以便访问生成的属性。或者干脆用一种特殊的方式来命名。但是,我不确定什么是最好的解决办法。我正在寻找干净的、符合良好实践的社区想法。谢谢
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
之类的属性放在分部类上,但我可以理解您可能需要分离的原因。下面是另一个使用显式接口的解决方案:
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使用显式接口使代码更可读,具有良好的可扩展性。是否可以强制该接口显式?当您具有默认可访问性并在属性/方法名称前加上接口名称时,该接口将显式实现。“明确性”在实现中,而不是在接口本身中。请注意,这些类不会绑定在MVC3Btw中,为什么要对这些自定义属性进行分组?有时您可以使用属性来标记它们。