简体   繁体   English

确定 class 在 C# 中调用了 static 方法

[英]Determining the class a static method was called on in C#

Suppose I have the following:假设我有以下内容:

class Parent
{
    public static string NameCalledOn()
    {
        Type t = ???;
        return t.Name;
    }
}

class Child : Parent
{
}

What could go in place of??? go 可以代替什么??? to determine which class (Parent or Child) was specified in a call to NameCalledOn?确定在对 NameCalledOn 的调用中指定了哪个 class(父或子)? Eg:例如:

Parent.NameCalledOn() should return "Parent" and Child.NameCalledOn() should return "Child". Parent.NameCalledOn()应该返回“Parent”,而Child.NameCalledOn()应该返回“Child”。

I saw mention of MethodBase.GetCurrentMethod().DeclaringType but that returns "Parent" for both.我看到提到MethodBase.GetCurrentMethod().DeclaringType但两者都返回“父级”。

Why I would want to do this: The URL-building helpers in ASP.NET MVC require the name of the controller and the name of the method.为什么我要这样做:ASP.NET MVC 中的 URL 构建助手需要 controller 的名称和方法的名称。 I don't want to use literal strings (typo-prone), and using nameof(MyController) doesn't work because it expects the name of the controller without the "Controller" suffix.我不想使用文字字符串(易错字),并且使用nameof(MyController)不起作用,因为它需要没有“Controller”后缀的 controller 的名称。 The shortest way I can think of is to create a get-only "Name" property on my base controller which determines which actual controller class the call was made on and returns its name with "Controller" chopped off.我能想到的最短方法是在我的基础 controller 上创建一个仅获取的“名称”属性,该属性确定哪个实际的 controller class 的名称被切断并返回。

Note that I'm using .NET Core 3.1, so this can include features from any C# version 3.1 supports.请注意,我使用的是 .NET Core 3.1,因此这可以包括来自任何 C# 版本 3.1 支持的功能。

Static's are not meant for usual inheritance rules of C#.静态不适用于 C# 的常规 inheritance 规则。

Making the method NameCalledOn() instance method will work the best.使方法 NameCalledOn() 实例方法效果最好。 There is no harm, all methods are loaded only once in memory for all instances.没有害处,所有方法在 memory 中对所有实例仅加载一次。 Data members for each instance consume separate memory but methods do not.每个实例的数据成员使用单独的 memory 但方法不使用。

Static method is not overridable, so the only way to achieve it is overwrting. Static 方法不可覆盖,因此实现它的唯一方法是覆盖。

class Parent
{
    public static string NameCalledOn()
    {
        return "Parent";
    }
}

class Child : Parent
{
    public new static string NameCalledOn()
    {
        return "Child";
    }
}

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

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