日期:2014-05-20  浏览次数:21048 次

【C#】考你一个输出“Hello World”程序
前天同学问我这样一个面试题:完成如下代码,使其输出“Hello World!”
C/C++ code
if() printf("Hello");
else printf(" World!");
我很快想到了答案。然后同学告诉我这个题不止一个答案。

如果换成C#,也可以这样问:完成如下代码,使其输出“Hello World!”
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            if (/* 补充这里 */)
                Console.Write("Hello");
            else
                Console.Write(" World!");
        }
    }
}

用C#语言,至少我已经想到了三种不同原理的答案。

欢迎大家想出更多的答案。

我会在若干天以后公布我所想到的答案。

------解决方案--------------------
using System; 
public class HelloWorld 

public HelloWorld() 

Console.WriteLine("HELLO WORLD"); 

public static void Main() 

HelloWorld hw = new HelloWorld(); 




using System; 
public class HelloWorld 

public void helloWorld() 

Console.WriteLine("HELLO WORLD"); 


public static void Main() 

HelloWorld hw = new HelloWorld(); 
hw.HelloWorld(); 


using System; 
interface IHelloWorld 

void writeHelloWorld(); 

public class HelloWorld : IHelloWorld 

public void writeHelloWorld() 

Console.WriteLine("Hello World"); 

public static void Main() 

HelloWorld hw = new HelloWorld(); 
hw.writeHelloWorld(); 




------解决方案--------------------
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Convet.ToBool(Console.Write("Hello")))
                Console.Write("Hello");
            else
                Console.Write(" World!");
        }
    }
}

------解决方案--------------------
探讨
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
……

------解决方案--------------------
洗耳恭听
------解决方案--------------------
2楼答案不行的,首先改为这样吧:Convert.ToBoolean (Console.Write("Hello")) 。然后还是
错误 参数“1”: 无法从“void”转换为“object”,继续关注
------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            if (new Func<bool>(() => { Console.Write("Hello"); return false; }).Invoke())
                Console.Write("Hello");
            else
                Console.Write(" World!");
        }
    }
}

------解决方案--------------------