方法可以确定调用者是否期望返回值吗? [英] Can a method determine if caller is expecting a returned value?

查看:82
本文介绍了方法可以确定调用者是否期望返回值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

给出:


public class myClass
{
  public int DoThis()
  {
    // Can this method determine if caller wants a returned value?
    return 1;
  }
}

  public static myClass MyClass = new myClass();

  MyClass.DoThis(); // Does not want a returned value.
  int i = MyClass.DoThis(); // Needs a returned value.

推荐答案

R-F-M,

我宁愿定义两种方法.我将使用其中一个返回另一个内部的值.这样,我的逻辑就可以放在一个地方(模块化的目标).这也将导致更好的设计,因为这些方法将仅执行它们的单个操作. 责任.

I would rather define two methods. I would use one which returns a value inside the other. In this way, my logic would be at a single place (the goal of modularity). This also would lead to a better design as the methods would be just performing their single responsibilities.

注意:如果您的呼叫者不需要返回的值,只需让被呼叫者返回该值即可,不要使用它.

Note: If your caller doesn't need the returned value, just let the callee return the value and don't use it.

如果您仍然想这样做,则可以从StackTrace of Environment中找出调用者.这样可以使您对调用方有所了解.
http://msdn.microsoft.com/en-us/library/system.environment. stacktrace.aspx

If you still want to do it then you can figure out the caller from StackTrace of Environment. This can give you some idea about the caller.
http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx

或者,您可以使用StackTrace类.这将为您提供有序的StackFrame.然后,您可以使用反射来查找有关呼叫者的信息

Alternatively, you can use StackTrace class. This would give you and ordered collection of StackFrame (s). You can then use reflection to find out information about the caller

http://msdn.microsoft.com/en-us/library/system .diagnostics.stacktrace.aspx

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

谢谢,
穆罕默德
shujaatsiddiqi.blogspot.com

Thanks,
Muhammad
shujaatsiddiqi.blogspot.com


这篇关于方法可以确定调用者是否期望返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆