呼叫者信息隐式传递参数

时间:2019-05-09 15:22:27

标签: c# attributes compiler-services

我已经开始使用Caller Information,发现它对工作非常有用。 我必须使用Factory模式来创建带有调用者信息的对象。

有什么方法可以通过工厂模式隐式传递呼叫者信息?

public class MyClass 
{
  MyClass(
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string methodName = null,
    [CallerFilePath] string filePath = null
  )
  {
     Console.WriteLine(methodName);
  }

}

public static class Factory {
  // What I currently use which works as expected.
  public static MyClass CreateMyClassExplicity(
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string methodName = null,
    [CallerFilePath] string filePath = null
  )
  {
     return new MyClass(lineNumber, methodName, filePath);
  }

  // How I would like to use it.
  public static MyClass CreateMyClassImplicitly(
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string methodName = null,
    [CallerFilePath] string filePath = null
  )
  {
     return new MyClass();
  }
}

0 个答案:

没有答案