开发者

Extension method using non Instantiated object, i.e. String.F()

开发者 https://www.devze.com 2023-04-04 21:46 出处:网络
At a previous organization, we implemented an extension method that created a shorthand for String.Format.The method was called \"String.F\". However I do not seem to be able to get this to work.A for

At a previous organization, we implemented an extension method that created a shorthand for String.Format. The method was called "String.F". However I do not seem to be able to get this to work. A former co-worker gave me the following code which I am listing below along with my own test method. In the function 'Test()', "String.F" throws and error and is not displayed in intellisence. I would ask if this is not possible, but I have writen code using a call to this method. Is this only possilble when using an instantiated string? Thanks.

public static class MyExtensions {
    public static string F(this string target, params object[] args) {
        return "hello";
    }
}

class TestExtensions {
    public string Test() {
        return String.F("test:{0}",开发者_运维技巧 "test");
    }
}


You cannot do extension method and use it in a static context. Extension methods can be used only as instance methods.

You can do

public static string F(this string target, params object[] args) {
        return String.Format(target, args);
}

and use it like this

"test:{0}".F("test");


I think the problem is you're invoking String.F, when the class that owns the method is MyExtensions; not String...if you want to invoke it like that, it should be MyExtensions.F("test{0}", "test")

As others have mentioned, though, while this is perfectly valid, it seems to be sidestepping the very thing that makes extension methods distinct.

Doing "test{0}".F("test"); should give the same result as MyExtensions.F("test{0}", "test"); If F wasn't set up as an extension method, only the latter approach would be valid.

0

精彩评论

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

关注公众号