【发布时间】:2016-11-16 07:52:16
【问题描述】:
假设我们有以下类:
public class Employee
{
public string Name { get; private set; }
public string Team { get; private set; }
public Employee(string name, string team)
{
this.Name = name;
this.Team = team;
}
public void UpdateName(string newName, string updatedBy)
{
this.Name = newName;
this.Update(updatedBy);
}
public void UpdateTeam(string newTeam, string updatedBy)
{
this.Team = newTeam;
this.Update(updatedBy);
}
private void Update(string updatedBy)
{
// and do something with updatedBy
}
}
在 C# 中是否有更好的方法可以强制执行方法(例如 UpdateTeam 调用 Update 方法并将字符串参数传递给它 - 例如 updatedBy)?
当然没有这样的语法,只是为了说明我的意思:
public class Employee
{
// ...
public void UpdateTeam(string newTeam, string updatedBy) : Update(updatedBy)
{
this.Team = newTeam;
}
private void Update(string updatedBy)
{
// and do something with updatedBy
}
}
编辑:我知道“模板”模式,这不是我需要的。
【问题讨论】:
-
非声明式 - 您可以通过单元测试验证您是否获得了正确的结果,但没有强制执行特定实现的机制。
-
您可以使用 Postsharp 之类的工具查看 Aspect-oriented programming。