Skip to main content
 首页 » 编程设计

c#之使用调用方法名称作为条件语句的条件

2024年02月13日13itcoder

是否可以获取调用方法的名称,并根据这些结果执行代码?

下面,我有两个用于数据库CRUD操作的方法。一个将对象添加到数据库,另一个更新。两者都返回一个对象,其中包含操作的统计报告。

在某些情况下,如果 Update 方法将 stat-o​​bj 返回给 Add 方法,我不会费心更新操作 stat 对象的 pkey 字段。

public OperationStat Add(object obj) 
{ 
  // Contains operation status data. 
  OperationStat op = new OperationStat(); 
  op.PrimaryKey = pkey.newkey(); 
 
  // Record to update 
  Person pete = new Person(); 
 
  // call update method. 
  op = this.Update(pete); 
} 
 
public OperationStat Update(object obj) 
{ 
  OperationStat op = new OperationStat(); 
  string callmethod = "Add"; 
 
  // Get stacktrace. 
  StackTrace stackTrace = new StackTrace(); 
  StackFrame stackFrame = stackTrace.GetFrame(1); 
  MethodBase methodBase = stackFrame.GetMethod(); 
 
  if(methodBase.Name != callmethod) 
  { 
   // create new primary key for status. 
   op.Primarykey = pkey.newkey(); 
  } 
 
  // fill operation stat object with details 
  return op; 
} 

请您参考如下方法:

.NET 4.5 引入了一些新属性,可以为您提供此类信息。

CallerMethodNameAttribute :

Allows you to obtain the method or property name of the caller to the method.


public OperationStat Update(object obj, [CallerMethodName] string calledFrom = "") 
{ 
  OperationStat op = new OperationStat(); 
  string callmethod = "Add"; 
 
  if(calledFrom != callmethod) 
  { 
    op.Primarykey = pkey.newkey(); 
  } 
 
  return op; 
}