des_null 2019-10-28 08:51 采纳率: 0%
浏览 1820

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 11:08
    关注

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

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

    评论
编辑
预览

报告相同问题?