简体   繁体   English

如何通过实例在非静态方法内部调用静态方法

[英]how to call static method inside non static method through instance

I understand that we could use the class name.method but I was wondering if there was a way to do it through an instance. 我知道我们可以使用类name.method,但是我想知道是否存在通过实例进行操作的方法。 Can you provide me an example also. 你能给我一个例子吗? The reason I'm asking is because my professor said: 我问的原因是因为我的教授说:

You MUST invoke the extension method using calls that use the static call form and the instance call form 您必须使用使用静态调用形式和实例调用形式的调用来调用扩展方法

With the edit that this is talking about extension methods, then it becomes easier! 通过编辑,它正在讨论扩展方法,然后变得更加容易!

With the same example as below: 与以下相同的示例:

bool hasValue1 = s.HasValue(); // use the instance syntax
bool hasValue2 = StringExtensions.HasValue(s); // use the static syntax

Note that these are 100% identical; 请注意,这些是100%相同的; once compiled to IL you cannot determine which form was used. 编译为IL后,您将无法确定使用哪种形式。


Short answer: "no", per CS0176: 简短答案:根据CS0176,“否”:

CS0176 Member '{name}' cannot be accessed with an instance reference; CS0176无法使用实例引用访问成员'{name}'; qualify it with a type name instead 用类型名称代替它

Slightly longer answer: if you really want to do that, maybe extension methods are what you are looking for; 稍微长一点的答案:如果您确实想这样做,那么扩展方法可能就是您想要的; for example: 例如:

static class StringExtensions
{
    public static bool HasValue(this string value)
    {
        return !string.IsNullOrEmpty(value);
    }
}
class Program
{
    static void Main()
    {
        string s = /* some string or null reference */
        bool hasValue = s.HasValue();
    }
}

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

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