首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

小小新手,有关问题有点白痴,望解答

2013-07-16 
小小新手,问题有点白痴,望解答using Systemusing System.Collections.Genericusing System.Linqusing S

小小新手,问题有点白痴,望解答
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApplication4
{
    class fuzhi
    {
     private   int a=0;
     private   int b=0;
        public int A
        {
            get {
                return a;
            }
            set {
                a = value;
            }
        }
        public int B
        {
            get {
                return b;
            }
            set {
                b = value;
            }
        }
    }
    class add {
        fuzhi b=new fuzhi();
        public int d (){
            return b.A + b.B;
        }
    }
    class Program
    {
       
        static void Main(string[] args)
        {
            //Program program = new Program();
            fuzhi a = new fuzhi();
            


            add eee = new add();
           a.A = 1;
            a.B = 2;
            Console.WriteLine(eee.d());
            Console.ReadLine();
        }
    }
}
这一段代码,不知道为啥执行出来的结果不是3,而是0.而且对应的在
class add {
        fuzhi b=new fuzhi();
        public int d (){
            return b.A + b.B;
        }
    }中,为什么创建了类fuzhi的对象b之后,不能直接用b.A=1;这样的复制
[解决办法]

class add
    {
        fuzhi b = null;

        public add(fuzhi bb)
        {
            this.b = bb;
        }

        public int d()
        {
            return b.A + b.B;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            fuzhi a = new fuzhi();
            a.A = 1;
            a.B = 2;

            add eee = new add(a);



            Console.WriteLine(eee.d());
            Console.ReadLine();
        }
    }


[解决办法]
引用:
class add
    {
        fuzhi b = null;
 
        public add(fuzhi bb)
        {
            this.b = bb;
        }
 
        public int d()
        {
            return b.A + b.B;
        }
    }
这个this去不去掉有没有区别,另外我查了下this是表示当前实例的意思,这里是当前实例的意思吗?有点不太明白。


不能去掉,this.b = bb;这里表示将bb的对象赋值给fuzhi b = null;中的b,通过构造函数将对象传过来。
你原来的那个为0,就是因为对象没有传过来,为null,所以值都是为0.

热点排行