好好的 Foo
被折腾成了什么样子
血流成河 惨不忍睹呀
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main()
{
string s1 = Foo1().ToString();
string s2 = Foo2();
Console.WriteLine( s1 );
Console.WriteLine( s2 );
Console.ReadLine();
}
static int Foo1()
{
return 6;
}
static string Foo2()
{
return (6).ToString();
}
}
}
以下是对
Thinking in C++, 2nd ed. Volume 1 的断章取义
Overloading on return values
It’s common to wonder, “Why just scopes and argument lists? Why not return values?” It seems at first that it would make sense to also decorate the return value with the internal function name. Then you could overload on return values, as well:
void f();
int f();
This works fine when the compiler can unequivocally determine the meaning from the context, as in int x = f( );. However, in C you’ve always been able to call a function and ignore the return value (that is, you can call the function for its side effects). How can the compiler distinguish which call is meant in this case? Possibly worse is the difficulty the reader has in knowing which function call is meant. Overloading solely on return value is a bit too subtle, and thus isn’t allowed in C++.
恩 说的不错
可问题是 不是说 C# 以后可以这样吗?
var i = 6;
var s = "6";
那为什么不可以这样呢?
int i = Foo();
string s = Foo();
ref
http://www.cnblogs.com/Ninputer/archive/2005/11/04/269117.html
在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();
posted on 2005-11-04 16:30
[ IceSharK - PP.Poet ] 阅读(3153)
评论(-1) 编辑 收藏 所属分类:
OO