我创建了两个类来替换Point的函数(两个变体),只是为了测试它们,我是这样创建它们的:
Entity.cs:
namespace Xnagame
{
class Player
{
public class float2
{
public float X { get; set; }
public float Y { get; set; }
}
public class int2
{
public int X { get; set; }
public int Y { get; set; }
}
public int2 Position { get; set; }
public int angle { get; set; }
public float speed { get; set; }
public float2 velocity { get; set; }
public Player CreatePlayer()
{
Position = new Player.int2();
Player player = new Player();
return player;
}
}
}如您所见,两个Point类都有一个X和Y变量(我不确定这是否是设置它们的方法,如果不是,请告诉我),这些类用于CreatePlayer()方法中实例化的位置和速度实例。
Game1.cs:
namespace Xnagame
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Texture2D playerimage;
private Texture2D background;
Player player = Player.CreatePlayer();现在的问题是,当CreatePlayer()方法试图将它的" player“返回给本地播放器时,它会给出:
非静态字段、方法或属性
Xnagame.Player.CreatePlayer()需要对象引用。
错误。
我还用新关键字尝试了一下,它给了我:
Xnagame.Player.CreatePlayer()是一种方法,但使用起来像一种类型。
发布于 2014-12-23 13:44:37
问题在于,您正在使用实例方法来创建实例。
你有两个选择:
1)使用默认构造函数
class Player
{
// Other subclasses, and properties.
public Player()
{
// Note: I added the other instance value just for fun.
Position = new Player.int2();
velocity = new Player.float2();
}
}2)使用静态构造函数方法。(它们通常只在单例模式中使用。)
class Player
{
// Other subclasses, and properties.
public static Player CreatePlayer()
{
// Note how I created the instance variables for the player class,
// and I used a notation called "object initalizer" to set those properties
// when I create the Player instance.
var p = new Player.int2();
var v = new Player.float2();
Player player = new Player()
{
velocity = v,
Position = p
};
return player;
}
}发布于 2014-12-23 13:41:42
您的CreatePlayer方法是一个实例方法-换句话说,必须对一个现有实例调用它。您可能想使其静态:
public static Player CreatePlayer()然后,您应该删除Position = new Player.int2()行--创建播放机不应该更改现有播放机的位置。
(我还强烈建议将嵌套类型提取为不可变的顶级结构,并将它们重命名为类似于Int32Position和SinglePosition的结构,尽管您很可能会发现框架已经有类似的东西了。还应该使所有属性都遵循.NET命名约定。)
发布于 2014-12-23 13:43:47
您需要使用静态函数直接从这样的类调用
public static Player CreatePlayer()
{
//all the code
}https://stackoverflow.com/questions/27621509
复制相似问题