如何實現用返回值重載
今天[ IceSharK - PP.Poet ]很清純地提出了一個問題,如何能做到函數返回值重載?簡單的說,就是如何實現
string Test() {...}
int Test() {...}
然后通過接受方的上下文自動選取重載:
int i = Test();
string s = Test();
當然VB或者C#都是不允許這樣寫的。不過IL并沒有禁止這一寫法,事實上在VB或C#中有一種語法結構允許按照返回值選取相應的重載,那就是隱式類型轉換運算符(implicit operator或者Widening Operator CType)。通過輔助類的隱式類型轉換運算符,我們可以實現上述要求的語法。
class Foo
{
string TestString()
{
return "I'm a string";
}
int TestInt()
{
return 100;
}
public TestHelper Test()
{
return new TestHelper(this);
}
public struct TestHelper
{
Foo m_host;
public TestHelper(Foo host)
{
m_host = host;
}
public static implicit operator int(TestHelper helper)
{
return helper.m_host.TestInt();
}
public static implicit operator string(TestHelper helper)
{
return helper.m_host.TestString();
}
}
}
調用的語法非常之完美:
Foo f = new Foo();
int i = f.Test();
string s = f.Test();
怎么樣,并沒有使用很高深的語法,就實現了想要的東西。