des_null 2019-10-28 16:51 采纳率: 0%
浏览 1750

C#中自定义了一个类实例化后,系统判定对象为空

我定义了一个类Item

public class Item : MonoBehaviour
{
    public int ID { get; set; }
    public string Name { get; set; }
    public  ItemType Type { get; set; }
    public string Description { get; set; }
    public int SellPrice { get; set; }
    public int BuyPrice { get; set; }
    public Sprite Sprite { get; set; }

    public Item(int _id,string _name,ItemType _type,string _description,int _sellprice,int _buyprice,Sprite _sprite)
    {
        this.ID = _id;
        this.Name = _name;
        this.Type = _type;
        this.Description = _description;
        this.SellPrice = _sellprice;
        this.BuyPrice = _buyprice;
        this.Sprite = _sprite;
    }

    public Item()
    {
        this.ID = -1;
    }
}

然后实例化出来一个item对象




Item temp=new Item(
                (int)jsonData[i]["id"], 
                jsonData[i]["name"].ToString(), 
                (ItemType)System.Enum.Parse(typeof(ItemType), 
                jsonData[i]["type"].ToString()),
                jsonData[i]["description"].ToString(), 
                (int)jsonData[i]["sellprice"], 
                (int)jsonData[i]["buyprice"], 
                Resources.Load<Sprite>(jsonData[i]["sprite"].ToString())

用Debug.Log(temp==null);语句判断出来的结果是true,也就是对象为空,但是Debug.Log(temp.Description);语句输出对象的属性又能够得到正确信息。

请问有没有大佬知道原因??求告知,谢谢

  • 写回答

2条回答 默认 最新

  • 阿成_ 2019-10-28 19:08
    关注

    == null的判断是类似于C 类重载了==运算符。你new出来的对象实际是有的,因为是无效的所以== null为true。

    继承MonoBehaviour的脚本不能用new关键词创建对象,如果你只是想做数据类的话,不要继承MonoBehaviour,如果要继承MonoBehaviour就只能用AddComponent创建对象。

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘