Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - "Member cannot be accessed with an instance reference qualify it with a type name instead" and I DO use type name

I have an example code like this:

public class SimpleLogger
{
    private static SimpleLogger logger;
    private string path = null;

    protected SimpleLogger(string path)
    {
        this.path = path;
    }

    public static SimpleLogger Instance(string path)
    {
        if (logger == null)
        {
            logger = new SimpleLogger(path);
        }
        return logger;
    }

    public static void Info(string info)
    {
        string path = $"{logger.path}{DateTime.Now.ToShortDateString()}_Info.txt";
        using (StreamWriter writer = new StreamWriter(path))
        {
            writer.WriteLine($"{DateTime.Now} - {info}");
        }
    }
}

and when I call:

SimpleLogger.Instance("path").Info("info");

There's an error:
member cannot be accessed with an instance reference qualify it with a type name instead static method

But I DO use type name, don't I?

But when I call it like this:

SimpleLogger.Instance("path");
SimpleLogger.Info("info");  

it actually does work fine.

To make it work inline I have to make Info method non-static and then inline call work also fine. Why is that? I don't understand the mechanism here. Can someone explain? Is it beacuse Instance method returns SimpleLogger object and then info requires to be non-static to be able to work on an instance rather than a type?

question from:https://stackoverflow.com/questions/65840929/what-is-the-meaning-of-cs0176-error-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C#, instance methods can only be called on an instance, whereas static methods can only be called on a class/struct itself.

Why can't you chain Info onto SimpleLogger.Instance()?

Because SimpleLogger.Instance(...) returns an instance of SimpleLogger, and you are trying to call a static method on the returned value. The returned value is an instance of SimpleLogger, so you can't call a static method on it.

By making Info non-static, you enable it to be called on an instance. Therefore, you can call it on the return value of Instance().

One reason for your confusion might be that you don't see the instance of SimpleLogger in your chain of methods, so to better illustrate the idea of chaining methods, this:

SimpleLogger.Instance("path").Info("info");

is equivalent to:

SimpleLogger logger = impleLogger.Instance("path");
logger.Info("info");

See the instance of SimpleLogger now?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...