我想创建松散耦合的类(PlayerProfile
和PlayersManager
),并能够从{访问PlayerScore
属性(在PlayerProfile
中实现)的值{1}}(不了解PlayersManager
)
PlayerProfile
PS:我不知道使用接口是正确的方法还是有其他方法。
有什么想法可以实现吗? 谢谢
答案 0 :(得分:1)
详细说明我的评论
public interface IClass
{
int PlayerScore { get; }
}
public class ClassA : IClass
{
public int PlayerScore { get; } = 250;
}
public class ClassB
{
public ClassB(IClass aClass)
{
_aClass = aClass;
// Now you can use _aClass.PlayerScore in the other methods
}
private readonly IClass _aClass;
}
现在,在阅读更新的代码之后:
public interface IPlayerProfile
{
int PlayerScore { get; }
}
public class Player : IPlayerProfile
{
public int PlayerScore { get; } = 250;
}
public class PlayersManager
{
public Add(IPlayerProfile profile)
{
// Use profile.PlayerScore
}
}
答案 1 :(得分:0)
您可以使用构造函数注入。这是Dependency Injection Design Pattern。另请参阅:Dependency injection。
public class PlayersManager
{
private readonly IPlayer _player;
PlayersManager(IPlayer player)
{
_player = player;
}
public void Manage() // Example
{
int score = _player.PlayerScore;
...
}
}
Dependency injection frameworks可以自动创建并注入依赖项。它们的工作方式如下(当然,细节在不同的依赖注入框架之间有所不同):
在静态类中创建依赖项注入容器
public static class DI
{
public static SomeContainer Container { get; } = new SomeContainer();
}
在程序启动时注册您的服务
DI.Container.Register<IPlayer, PlayerProfile>();
DI.Container.Register<PlayersManager>();
然后使用以下内容创建一个PlayersManager
:
// This automatically creates a `PlayerProfile` object and a `PlayersManager` object by
// injecting the player profile into the constructor of the manager.
var pm = DI.Container.Resolve<PlayersManager>();
与
相同IPlayer temp = new PlayerProfile();
var pm = new PlayersManager(temp);