如何實現用返回值重載

作者: 裝配腦袋  來源: 博客園  發布時間: 2009-02-27 13:51  閱讀: 1853 次  推薦: 0   原文鏈接   [收藏]  

今天[ 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();

怎么樣,并沒有使用很高深的語法,就實現了想要的東西。

 

0
0
 
標簽:CLR
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()