简体   繁体   中英

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. 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; once compiled to IL you cannot determine which form was used.


Short answer: "no", per CS0176:

CS0176 Member '{name}' cannot be accessed with an instance reference; 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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