开发者

Way to add an Extension method?

开发者 https://www.devze.com 2023-01-14 00:17 出处:网络
Say I have a class called LogHelper and it has a static method called GetLogger(string name). Is there a way to add a sta开发者_StackOverflowtic extension method that would just be GetLogger()?

Say I have a class called LogHelper and it has a static method called GetLogger(string name).

Is there a way to add a sta开发者_StackOverflowtic extension method that would just be GetLogger()?

I know that normally extension methods are static where they are declared, but is there a way to appear static on the class they are "Helping"?


You could use an extension method:

public static class StringExtensions
{
    public static ILogger GetLogger(this string value)
    {
        ...
    }
}

And then you could use like this:

string foo = "bar";
ILogger logger = foo.GetLogger();


You can also use

    public static ILogger GetLogger(string value)
    {
        ...
    }

    public static ILogger GetLogger()
    {
        return GetLogger("Default Value");
    }

This way when you called GetLogger() it would call GetLogger(string value) but with your default value.


It is not possible to extend static classes with extension methods, unfortunately...

(I'm assuming your LogHelper is static? At least that's what I understood so far.)


I'm not sure how efficient this is, but it should work. log4net has an overload that accepts a Type, and you often want to name the logger after the fully qualified type name.

void Main()
{
    var foo = new Bar.Foo();
    ILog logger = foo.GetLogger();
}   

public static class LogHelper
{
    public static ILog GetLogger(this object o)
    {
        return LogManager.GetLogger(o.GetType());
    }
}

namespace Bar
{
    public class Foo {}
}

// Faking log4net
public class ILog {}
public class LogManager
{
    public static ILog GetLogger(Type type)
    {
        Console.WriteLine("Logger: " + type.ToString());
        return null;
    }
}

The above prints "Logger: Bar.Foo".

P.S. Use "this.GetLogger()" if you want a logger for the current class (assuming non-static method).


Since what you want is impossible, why not fake it?

After all, it doesn't really matter if your parameterless GetLogger() method is on LogHelper. Just write your own static class, called MyLogHelper or something, and define the method there. The code would look like this:

public static class MyLogHelper
{
    public static ILog GetLogger()
    {
        return LogHelper.GetLogger("MyHardcodedValue");
    }
}


I see only one solution is to use optional arguments, but unfortunately they appear only in C# 4.0:

public static class LogHelper
{
    public static ILogger GetLogger(string name = "DefaultLoggerName")
    {
        ...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消