简体   繁体   English

如何在对象C#中访问对象的属性

[英]How to access a property of an object within an object C#

I'm trying to make a code that reads the object property of an object before using said ability. 我正在尝试编写一个代码,以在使用所述功能之前读取对象的对象属性。 In this case, it reads the cooldown of the the ability, then casts the ability if the cooldown equals zero. 在这种情况下,它将读取技能的冷却时间,然后在冷却时间等于零时施放该技能。 However, I can't get the code to run without experiencing an error. 但是,如果没有遇到错误,我将无法运行代码。 It will not let me access the property. 它不会让我访问该属性。

public class Pug : Dogs
{
    public Pug()
    {
        ability bark = new Ability();
        bark.cooldown = 2;
    }

    public void PugBark()
    {
        if (bark.cooldown == 0)//error occurs on this line
        {
            //He Barks
        }
    }
}

because of your bark object the only available in the construct function scope. 因为您的bark对象是构造函数范围中唯一可用的对象。

I think you can try to let bark be a field or property in the Pug class 我认为您可以尝试让bark成为Pug类中的一个字段或属性

public class Pug : Dogs , ThingsDogsDo
{
    private Ability bark;

    public Pug()
    {
        bark = new Ability();
        bark.cooldown = 2;
    }

    public void PugBark()
    {
        if (bark.cooldown == 0)//error occurs on this line
        {
            //He Barks
        }
    }
}

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

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