简体   繁体   English

如何即时返回方法的完全限定名称?

[英]How to return a method's fully-qualified name on the fly?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        //
        // GET: /Store/

        public string Index()
        {
            return "MvcMusicsStore.Controllers.StoreController.Index";
        }

    }
}

How to return a method's fully-qualified name on the fly?如何即时返回方法的完全限定名称?

Without any hard coding?没有任何硬编码? Something like maybe?可能是什么?

public string Index()
{
    return GetType().FullName + GetMemberName();
}

static string GetMemberName([CallerMemberName] string memberName = "")
{
    return memberName;
}

Or perhaps prettier:或者更漂亮:

public string Index()
{
    return GetMemberName(this);
}

static string GetMemberName(
    object caller, [CallerMemberName] string memberName = "")
{
    return caller.GetType().FullName + "." + memberName;
}

(I used static because I assume in the real code you'd want to put the method in a utility class somewhere) (我使用static是因为我假设在实际代码中您希望将该方法放在某个实用程序类中)

If you're using C# 5 you can do this slightly more simply, but this works too:如果您使用的是 C# 5,则可以稍微简单地执行此操作,但这也可以:

var method = MethodBase.GetCurrentMethod();
var type = method.DeclaringType;
var fullName = string.Format("{0}.{1}", type.FullName, method.Name);

That's assuming the method isn't overridden, of course.当然,这是假设该方法没有被覆盖。 Unfortunately you can't put this into a utility method of course, as otherwise the current method is the utility method.不幸的是,您当然不能将其放入实用程序方法中,否则当前方法就是实用程序方法。

You can use StackTrace to get round this, but you need to be careful around inlining - if you create a utility method and then call it from within a method which is itself inlined, you'll get the caller of the method you want :(您可以使用StackTrace来解决这个问题,但您需要小心内联 - 如果您创建一个实用方法,然后从本身内联的方法中调用它,您将获得所需方法的调用者:(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM