C#:保护级别错误

C#:保护级别错误,c#,unit-testing,C#,Unit Testing,=============== 你看,这就是让我难过的原因 这段代码来自《C#Game Programming:用于严肃游戏创作》一书 我从这本书的CD-ROM上得到了完全相同的代码。示例代码很好,而我的代码有一个错误 这是我第一次用C编写游戏代码。然而,正如我所理解的,我的应该有效。但是,看起来编译器并不这么认为 我怎样才能解决这个问题 //Page 40: Unit Test for Player class //Player must have a health that is great

===============

你看,这就是让我难过的原因

这段代码来自《C#Game Programming:用于严肃游戏创作》一书

我从这本书的CD-ROM上得到了完全相同的代码。示例代码很好,而我的代码有一个错误

这是我第一次用C编写游戏代码。然而,正如我所理解的,我的应该有效。但是,看起来编译器并不这么认为

我怎样才能解决这个问题

//Page 40: Unit Test for Player class
//Player must have a health that is greater than 0
//When the character is created.

namespace UnitTestingSample
{

    class PlayerTests
    {
        public bool TestPlayerIsAliveWhenBorn()
        {
            Player p = new Player(); //ERROR: 'UnitTestingSample.Player.Player()' is inaccessible due to its protection level

            if (p.Health > 0)
            {
                return true; //pass test
            }

            return false; //fail test

        }//end function

    }//end class

}//end namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Page 41
//Player class has default health which is 10
//when his character is created
namespace UnitTestingSample
{

    class Player
    {
        public int Health { get; set; }

        Player() //constructor
        {
            Health = 10;
        }
    }
}

默认情况下,类成员是私有的,构造函数也是私有的,这导致测试代码无法访问。如果您想从类本身以外的其他地方访问构造函数,请将其公开。

我遇到了类似的问题,发现这篇博客文章非常有用

它建议的具体解决方案是将以下行添加到要测试AssemblyInfo.cs文件的项目中

class Player
{
    public int Health { get; set; }

    public Player() //constructor
    {
        Health = 10;
    }
}
(其中TestProject更改为测试项目程序集的名称)

以及右键单击单元测试项目中的引用并向正在测试的项目添加引用


这只建议用于单元测试,因为它将两个项目紧密地结合在一起,并且会与正常的面向对象最佳实践背道而驰。

嘿,谢谢!因此,我认为构造函数肯定不是私有的,因为Player类不是私有的。在这种情况下,类是私有的,因为您没有另外指定,即
公共类Player
@mynameiscoffey提供非嵌套类型的默认保护级别,即
命名空间的直接成员类型,在C#术语中称为
内部
。只能从同一个“程序”,即同一个组件访问。
[assembly: InternalsVisibleTo("TestProject")]