public class Employee { // 只有SourceType== Salary 才转账 public void TransferToEmployee([TransferSource(TransferType = TransferSourceType.Salary)]int number) { //汇钱到银行卡 } } /// <summary> /// 转账类型 /// </summary> public enum TransferSourceType { Salary, Reimburse, Loan }
public class HR { public void ToSalary(Employee employee) {
// 使用元数据 var transferSource = typeof(Employee).GetMethod("TransferToEmployee").GetParameters()[0].GetCustomAttributes(false)[0] as TransferSource; if (transferSource.TransferType == TransferSourceType.Salary) { employee.TransferToEmployee(500); } else { employee.TransferToEmployee(0); } } }
Employee employee = new Employee(); HR hr = new HR(); hr.ToSalary(employee);