很少会有人可以答对,如果你遇到一个来面试的人实在嚣张,就可以用本文的题去打击 本文内容就看着玩,请不要在严肃的面试中问题这样的题目
如果面试到一个人可以回答出下面的题目也不能证明他的技术很强,只能说明他了解很多C#相关,或者他看过我的博客
请在下面的代码的注释处填写代码,让函数 Foo 里面的代码输出
static void Main(string[] args)
{
// 请在此处写代码,调用 Foo 函数内的输出代码
}
private static void Foo()
{
try
{
while (true)
{
}
}
finally
{
Console.WriteLine("尝试调用 Foo 函数执行这一句代码");
}
}
参考答案
使用一个线程调用的方式,调用之后结束线程,此时就会输出
static void Main(string[] args)
{
// 请在此处写代码,调用 Foo 函数内的输出代码
var thread = new Thread(Foo);
thread.Start();
Task.Delay(100).Wait();
thread.Abort();// 这时就会结束循环
Console.Read();
}
请写出 IFoo 和 Foo 的实现,让下面的代码不会抛出空异常
static void Main(string[] args)
{
Foo foo = (IFoo) null;
foo.Name = "lindexi";
Console.Read();
}
参考答案
class IFoo
{
}
class Foo
{
public string Name { get; set; }
public static implicit operator Foo(IFoo foo)
{
return new Foo();
}
}
请添加新的类的代码让下面的代码编译通过
class Program
{
static async Task Main(string[] args)
{
Foo foo = await (object) null;
foo.Name = "lindexi";
Console.Read();
}
}
public class Foo
{
public string Name { get; set; }
}
参考答案
public class HeabdsdnbKevx : INotifyCompletion
{
public bool IsCompleted { get; }
public Foo GetResult()
{
return new Foo();
}
/// <inheritdoc />
public void OnCompleted(Action continuation)
{
}
}
public static class RelelnisSou
{
public static HeabdsdnbKevx GetAwaiter(this object obj)
{
return new HeabdsdnbKevx();
}
}
再高级一点,写出下面的代码
static async Task Main(string[] args)
{
await await await await await await await await await await await await
await await await await await await await "林德熙是逗比";
}
其实很简单,也就是将 GetResult 修改一下,在上面的代码修改
public string GetResult()
{
return "林德熙是逗比";
}
因为返回值是 string 所以又可以继续等待
这里有一个代码,需要让 finally 里面的代码不执行,现在你只能写 Foo 方法,同时这个方法不能运行无限长时间
try
{
Foo();
}
finally
{
Console.WriteLine("不要让这个代码运行");
}
参考答案
因为不能让 Foo 运行无限长,就不能使用无限循环的方法,可以使用的方法有 Environment.FailFast 或 Environment.Exit 退出
private static void Foo()
{
Environment.Exit(0);
}