简体   繁体   English

空引用异常未在C#中处理

[英]Null reference exception was unhandled in c#

For example in section a: i have a random number and in the section b: i want to multiply that random number by 2 but it has to be in a function and then section c: has to add 10 and so on. 例如在a节中:我有一个随机数,在b节中:我想将该随机数乘以2,但它必须在函数中,然后c:节必须加10,依此类推。 I guess this is very simple for you guys. 我想这对你们来说非常简单。 and i am sure i am writing very silly codes but i am not a programmer. 而且我确定我在编写非常愚蠢的代码,但我不是程序员。

thanks. 谢谢。

class Program
{
    static void Main(string[] args)
    {
        Boot boot = new Boot();
        Game game = new Game();

        Console.WriteLine("Matrix Lengte: " + game.Matrix);
        Console.WriteLine("Lengte boot: " + boot.Lengte);

        Console.ReadLine();

class Game
{
    private Boot boot;
    private int matrix;

    public int Matrix
    {
        get { return matrix; }
        set { matrix = value; }
    }

    public Game()
    {    
        matrix= boot.Lengte*2;
    }

    internal Boot Boot
    {
        get { return boot; }
        set { boot = value; }
    }

By default fields have their default values, which is null for reference types. 默认情况下,字段具有其默认值,对于引用类型,该值为null So, just add boot initialization: 因此,只需添加boot初始化:

public Game()
{
    boot = new Boot(); // or pass via constructor parameter
    matrix = boot.Lengte * 2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM