简体   繁体   English

使用别名时无法隐式转换类型错误

[英]cannot implicitly convert type error when using aliases

I am new to learning C# and am coming from a C++ background. 我是学习C#的新手,并且来自C ++背景。 I am using an alias in the following manner: 我以以下方式使用别名:

using CreationFunction = Func<Microsoft.Xna.Framework.Vector2, GAShooter.Entity>;

Then in my class I have a dictionary like so: 然后在我的课堂上,我有一个像这样的字典:

private Dictionary<String, CreationFunction> creators;

However when I try to initialize it in the contstructor like this: 但是,当我尝试像这样在构造函数中初始化它时:

creators = new Dictionary<String, CreationFunction>();

I get an error. 我得到一个错误。 It says that it cannot implicitly convert the type. 它说它不能隐式转换类型。 What gives? 是什么赋予了?

EDIT: full code 编辑:完整代码

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

using CreationFunction = Func<Microsoft.Xna.Framework.Vector2, GAShooter.Entity>;

namespace GAShooter
{
    class EntityFactory
    {
        private Dictionary<String, CreationFunction> creators;

        public EntityFactory()
        {
            creators = new Dictionary<String, CreationFunction>();
        }

        public void RegisterCreator(String name, CreationFunction function)
        {
            creators[name] = function;
        }

        public Entity Create(String name)
        {
            var creator = creators[name];
            return creator();
        }
    }
}

and the full text for the error is: 错误的全文为:

cannot implicitly convert type 'Dictionary<string,Func <Microsoft.Xna.Framework.Vector2, GAShooter.Entity> to type 'Dictionary<String, CreationFunction>' 无法将类型'Dictionary<string,Func <Microsoft.Xna.Framework.Vector2, GAShooter.Entity>隐式转换为类型'Dictionary<String, CreationFunction>'

I think the problem is in your alias definition, you should change it to 我认为问题出在您的别名定义中,您应该将其更改为

using CreationFunction = System.Func<Microsoft.Xna.Framework.Vector2, GAShooter.Entity>;

Create a using alias to make it easier to qualify an identifier to a namespace or type. 创建using别名,以使将标识符限定为名称空间或类型变得更加容易。 The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it. using别名指令的右侧必须始终是标准类型,而不管其前面的using指令如何。

read more here . 在这里阅读更多。

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

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