如何才能更新以下代码以防止NullReferenceException? [英] how can the can the following code be updated to prevent the NullReferenceException?

查看:62
本文介绍了如何才能更新以下代码以防止NullReferenceException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面试中得到了这个问题,我不知道如何解决它。我回答这是不可能的,但实际上我不知道。我希望我能在这里得到比stackoverflow更聪明的答案。



不修改main方法中的任何代码,怎么能更新以下代码以防止NullReferenceException并将Hello World写入控制台?



I get this question during an interview and I have no idea how to resolve it. I answered this is impossible to do but actually I don't know. I hope I will get smarter answer here than on stackoverflow.

Without modifying any of the code inside the main method, how can the can the following code be updated to prevent the NullReferenceException and also write 'Hello World' to the console?

public class MyClass
{
}

public class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = null;
        Console.WriteLine(myObj.GetString()); // Will throw NullReferenceException
    }
}





这个问题的解决方案是什么?



What is the solution to this question?

推荐答案

如果你指定null到对象本身,然后调用,它会给出什么结果!亲爱的,这不是一个正确的方法,检查空值然后向前看。你需要在没有它的情况下更改代码,我认为我们不能。

谢谢

:)
If you are specifying null to the object itself and then invoking, what result would it give!! Dear this is not a right method to do, check for the null values and then look forward. You need change of code here without it, I dont think we can.
Thanks
:)


尝试使用扩展方法:



Try using Extension Methods:

public class MyClass
{
}

public class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = null;
        Console.WriteLine(myObj.GetString()); // Will throw NullReferenceException
    }
}

public static class Helper
{
    public static string GetString(this MyClass my)
    {
        return "hello world";
    }
}

//If .NET 2.0
//namespace System.Runtime.CompilerServices
//{
//    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
//    public sealed class ExtensionAttribute : Attribute { }
//}


实际上没有办法让它在指定的范围内工作。



无论你对MyClass类做什么,你总是会在Main中得到NullReference异常。
There really isn't a way to make it work within the bounds specified.

No matter what you do to the MyClass class, you will always get the NullReference exception in Main.


这篇关于如何才能更新以下代码以防止NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆