简体   繁体   English

是否可以将结构绑定到 Unity 中的接口?

[英]Is it possible to bind a struct to an interface in Unity?

I want configure Unity to resolve an interface, say ITest , to a struct, say struct Test .我想配置 Unity 以将接口(例如ITest )解析为结构(例如struct Test )。 So far I have next:到目前为止,我有下一个:

<unity>
    <containers>
        <container>
            <types>
                <type
                    type="my.ITest, asm" 
                    mapTo="my.Test, asm">
                </type>
            </types>
        </container>
    </containers>
</unity>

but I'm getting next error:但我收到下一个错误:

Resolution of the dependency failed, type = "my.ITest", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Test cannot be constructed. You must configure the container to supply this value.
At the time of the exception, the container was:    
Resolving my.Test,(none) (mapped from my.ITest,(none))

Why?为什么?

The problem is that you are trying to use Unity to construct a struct;问题是您正在尝试使用 Unity 构造一个结构; because a struct is a value type, Activator.CreateInstance is going to blow chunks when trying to create it (because of the interface).因为结构是值类型,所以 Activator.CreateInstance 在尝试创建它时会破坏块(因为接口)。

For example:例如:

 var item = Activator.CreateInstance<Test>();

Would throw an exception "Cannot create an instance of an interface".会抛出异常“无法创建接口的实例”。 Internally, Unity is probably using Activator.CreateInstance somewhere down the chain (I've been looking through Unity's code plex for a little while now), and that's where it will die.在内部,Unity 可能在链的某个地方使用了 Activator.CreateInstance(我已经查看了 Unity 的代码 plex 有一段时间了),这就是它会死的地方。

I'd suggest changing to a class implementation instead of a struct.我建议更改为 class 实现而不是结构。

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

相关问题 Unity-类,结构或接口成员声明中的意外符号“;” - Unity - Unexpected Symbol “;” in class, struct or interface member declaration 是否可以注册通用接口而无需在Unity中指定通用类型? - Is it possible to register a generic interface without specifying generic types in Unity? 'class、结构或接口成员声明中的无效标记'='。' 统一脚本中有两行错误 - 'Invalid token '=' in class, struct, or interface member declaration.' error with two lines in a unity script Unity:错误 CS1519:class、结构或接口成员声明中的标记“=”无效, - Unity: error CS1519: Invalid token '=' in class, struct, or interface member declaration, 添加Struct:接口到列表<Interface> - Adding Struct : Interface to a List<Interface> 如何将结构绑定到DropDownList - how to bind a struct to a DropDownList 了解Unity粒子系统中的“结构” - Understanding the “Struct” in Unity ParticleSystem 带有接口的Unity扩展了另一个接口 - Unity with interface that extends another interface 声明一个结构符合的接口 - Declare an interface that a struct conforms to 尝试运行此 Unity-C# 脚本时出现错误(class、结构或接口成员声明中的令牌“无效”无效) - I get an error while trying to run this Unity-C# Script (Invalid token 'void' in class, struct, or interface member declaration)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM