No. You can't. Compiler changes your extension method instance-like call to static method call anyway.
Is it possible to make an extension method aware of the syntax it is called by?
-
10-06-2023 - |
문제
Edit: The collective "Hey stupid" was a very nice reminder to re-think my original problem. My curiosity still stands on the subject so I've edited out the bad idea bits.
Given an extension method:
public static class Util {
public static string Triple<T>(this T t) {
var builder = new StringBuilder();
foreach (char c in t.ToString()) {
builder.Append(c, 3);
}
return builder.ToString();
}
}
I know I can call this method using either the instance member syntax,i.e. foo.Triple()
, or with static method syntax, Util.Triple(foo)
. Do I have a way to make the extension method aware of in which manner it is called? Consider (not valid C#):
public static class Util {
public static string Triple<T>(this T t) {
if (calledStatic) {
// do something if called by static syntax
} else {
// do something if not called by static syntax
}
var builder = new StringBuilder();
foreach (char c in t.ToString()) {
builder.Append(c, 3);
}
return builder.ToString();
}
}
I've checked the C# language specification, specifically regarding extension methods, SO questions, and am at a loss.
Bottom line version: Can I make an extension method aware of the manner in which it is called?
해결책
다른 팁
That's not possible. Extension methods are just "compiler magic", the compiled version of foo.Triple()
will look like Util.Triple(foo)
anyway.