首页 \ 问答 \ C#依赖注入(C# Dependency Injection)

C#依赖注入(C# Dependency Injection)

我试图看看我是否理解了依赖注入。

我有一个用作解析器的项目。 它可以解析分隔文本,键值以及正则表达式。

这样做的第一种方法是使用开关的一个功能。 下一个方法是将其置于单独的功能中并基于开关调用它

我想的另一种方法是创建一个接口,而不是为每种类型实现一个类。 那是多少工作? 这个问题是否起作用或将会显示出我尚未看到的好处。

我相信我的问题源于我最初要实现一个接口,而且每次我需要一个不同的解析器实现一个新类。 但是,这仍然需要我进入并将其添加到某种类型的逻辑流程中,因为我没有看到如何使用注入框架来实现这一点。

所以说我以另一种方式添加解析基于标签或xml。 创建实现接口的类,而不是我需要将它们添加到流逻辑中,以便在用户选择解析该类型的文本时将它们实例化为该接口。 有任何明确的方法吗?


I'm trying to see if I understand depedency injection.

I have a project that is used as a parser. It can parse delimited text, key-value and will also regex.

The first way this was done was in one function with a switch. The next way was to put it in seperate functions and call it based on a switch

The next way I was thinking was to create an interface and than implement a class for each type. Is that to much work? Does the question come down to function or will doing this show benefits that I don't see yet.

I believe my problems stems that I was initially going to implement an interface and than for each time I needed a different parsing implement a new class. But than that would still require me going in and adding that to some type of logic flow as I don't see how to do that with injection frameworks.

So say I add in another way to parse that is based on tags or xml. Create the class implementing the interfaces and than I would need to add them to the flow logic to instantiate them as that interface if a user chooses to parse that type of text. Any clearner way to do that?


原文:https://stackoverflow.com/questions/5284627
更新时间:2024-03-11 21:03

最满意答案

如果正确使用用户默认值,则应该能够从任何对象读取和写入,因为UserDefaults.standard是单例。 这些方面的东西应该有效:

private let scoreUserDefaultsKey = "scoreUserDefaultsKey"

func save(score: Int)
{
    let userDefaults = UserDefaults.standard
    userDefaults.set(score, forKey: scoreUserDefaultsKey)
    userDefaults.synchronize()
}

func read() -> Int
{
    return UserDefaults.standard.integer(forKey: scoreUserDefaultsKey)
}

class GameScene1: SKScene {

    func saveFromGameScene1(score: Int) {
        save(score: score)
    }
}

class GameScene2: SKScene {

    func readFromGameScene2() -> Int {
        return read()
    }
}

说你可以拥有一个更好的架构来实现一个ScoreManager对象并将它注入游戏场景中(而不是将单个硬件依赖于它)。

更新:刚刚看到你的代码片段。 您需要使用set ,而不是setValuesetValue不是UserDefaults的方法,而是KSO的NSObject方法。

func setValue(_ value:Any?,forKey key:String)

将给定键指定的接收器的属性设置为给定值。 如果key标识了一对一的关系,则将value指定的对象与接收者关联,如果存在,则与先前相关的对象无关。 给定一个集合对象和一个标识多对多关系的密钥,将集合中包含的对象与接收者联系起来,如果有的话,则与先前相关的对象无关。

setValue:forKey:uses的搜索模式在“键值编码编程指南”中的“访问器搜索模式”中进行了描述。

在引用计数环境中,如果直接访问实例变量,则保留值。

这不是你想要的;)

在调用set之后,请确保同时调用synchronize以确保该值立即存储。

我希望这有帮助。


If you use user defaults correctly you should be able to read and write from any object as UserDefaults.standard is a singleton. Something along these lines should work:

private let scoreUserDefaultsKey = "scoreUserDefaultsKey"

func save(score: Int)
{
    let userDefaults = UserDefaults.standard
    userDefaults.set(score, forKey: scoreUserDefaultsKey)
    userDefaults.synchronize()
}

func read() -> Int
{
    return UserDefaults.standard.integer(forKey: scoreUserDefaultsKey)
}

class GameScene1: SKScene {

    func saveFromGameScene1(score: Int) {
        save(score: score)
    }
}

class GameScene2: SKScene {

    func readFromGameScene2() -> Int {
        return read()
    }
}

Said that you could have a much nicer architecture implementing a ScoreManager object and inject it (instead of having hard dependencies on a singleton) into your game scenes.

UPDATE: Just seen your code snippet. You need to use set, not setValue. setValue is not a method of UserDefaults but is a method of NSObject for KVO.

func setValue(_ value: Any?, forKey key: String)

Sets the property of the receiver specified by a given key to a given value. If key identifies a to-one relationship, relate the object specified by value to the receiver, unrelating the previously related object if there was one. Given a collection object and a key that identifies a to-many relationship, relate the objects contained in the collection to the receiver, unrelating previously related objects if there were any.

The search pattern that setValue:forKey: uses is described in Accessor Search Patterns in Key-Value Coding Programming Guide.

In a reference-counted environment, if the instance variable is accessed directly, value is retained.

That is not what you're looking for ;)

Also after you call set make sure to call synchronize as well to be certain that the value is stored immediately.

I hope this helps.

相关问答

更多
  • 你可以对你的代码做的最简单的改变是让你的单例类持有一个ObservableList而不是一个List 。 然后,您可以直接在表格视图中使用它,并直接在其他控制器中更新它。 由于表格视图观察其支持列表,所以可观察列表的更改将立即反映在表格中。 即 import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class Datas { // SINGLETON PATTERN ...
  • 如果正确使用用户默认值,则应该能够从任何对象读取和写入,因为UserDefaults.standard是单例。 这些方面的东西应该有效: private let scoreUserDefaultsKey = "scoreUserDefaultsKey" func save(score: Int) { let userDefaults = UserDefaults.standard userDefaults.set(score, forKey: scoreUserDefaultsKey) ...
  • 根据文档,您应该传递一个boolean值,而您的reset值与我所看到的无关! scene = scene.destroy(true); scene = null; # Also the controller controller.destroy(true); controller = null; 这是你应该使用的。 在scrollmagic网站上也有一个很好的例子, 请查看 According to the documentation you should pass a boolean value an ...
  • 您必须确保您的变量不在任何函数或类之外,除非您想使用这些方法来调用变量。 在任何块之外定义的变量将可用于整个应用程序。 如果你的var是在一个块中定义的,那么你需要使用该块来调用它。 struct getMoney { var money: Int = 100 } 你可以像...一样访问它 var playerMoney = getMoney.money You have to make sure that your variable is outside of any functions or cla ...
  • 尝试这个: class GameSKView: SKView { internal var mylevel = 0 } 在你的主要游戏场景里面 if let gameView = self.view as GameSKView { sample.text = "my level is :\(gameView!.mylevel)" } Finally found the solution. In order to use the custom SKView, I have done t ...
  • 要通过执行CS.Score来访问它,您需要将该属性设置为静态 。 静态变量/方法属于类本身(在本例中为CS),如果不是静态的,则它们属于该类的实例(例如var csInstance:CS = new CS(); csInstance.Score = 6; ) 以下是如何使其静态: package file_as{ public class CS{ public static var Score:Number = 0; } } 顺便说一句,您当前的类代码应该抛出错误,因 ...
  • cocos2d中存在CCScene的唯一原因是因为CCDirector需要它作为runWithScene和replaceScene等方法的基类。 除此之外,CCScene,CCLayer和CCNode几乎完全相同。 您可以为场景,图层,节点,精灵等提供所需的任何角色。 但是,通常场景承担当前活动游戏对象(节点)的状态管理器的角色。 一个常见的用例是将场景声明为单例,以便任何子节点都可以访问场景的基本方法,例如发送其他不相关的节点消息,或者检查游戏是否结束,等等。 对于传播事件我赞成传递事件,因为没有简单的方 ...
  • 我在一个昵称Jasamer的reddit家伙的帮助下弄明白了。 盖伊摇滚。 这是我改变的: 当场景被改变时 let scene = GameOverScene(size: skView.bounds.size) 我补充说: scene.gameScene = self scene.score = score 然后,GameOverScene: class GameOverScene: SKScene { var gameScene = GameScene() override ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)