使用别名时无法隐式转换类型错误
cannot implicitly convert type error when using aliases
我刚开始学习 C#,并且有 C++ 背景。我通过以下方式使用别名:
using CreationFunction = Func<Microsoft.Xna.Framework.Vector2, GAShooter.Entity>;
然后在我的 class 中有一个这样的字典:
private Dictionary<String, CreationFunction> creators;
然而,当我尝试在构造函数中像这样初始化它时:
creators = new Dictionary<String, CreationFunction>();
我收到一个错误。它说它不能隐式转换类型。是什么赋予了?
编辑:完整代码
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();
}
}
}
错误的全文是:
cannot implicitly convert type 'Dictionary<string,Func <Microsoft.Xna.Framework.Vector2, GAShooter.Entity>
to type 'Dictionary<String, CreationFunction>'
我认为问题出在您的别名定义中,您应该将其更改为
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. The right side of a using alias directive must
always be a fully-qualified type regardless of the using directives
that come before it.
阅读更多 here。
我刚开始学习 C#,并且有 C++ 背景。我通过以下方式使用别名:
using CreationFunction = Func<Microsoft.Xna.Framework.Vector2, GAShooter.Entity>;
然后在我的 class 中有一个这样的字典:
private Dictionary<String, CreationFunction> creators;
然而,当我尝试在构造函数中像这样初始化它时:
creators = new Dictionary<String, CreationFunction>();
我收到一个错误。它说它不能隐式转换类型。是什么赋予了?
编辑:完整代码
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();
}
}
}
错误的全文是:
cannot implicitly convert type
'Dictionary<string,Func <Microsoft.Xna.Framework.Vector2, GAShooter.Entity>
to type'Dictionary<String, CreationFunction>'
我认为问题出在您的别名定义中,您应该将其更改为
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. The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it.
阅读更多 here。