获取类的每个实例的类属性数据

  • 本文关键字:属性 数据 实例 获取 c#
  • 更新时间 :
  • 英文 :


我不确定这是否可能与c#,但是有可能在与类的实例相关的属性中存储信息吗?

所以,我有以下类的字段Initialized,如下所示:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class GameObjectAttribute : Attribute {
internal bool Initialized = false;
}

然后我用它来添加属性到类:

[GameObject]
public class Player {
}

现在,在这个类中,是否可以像下面的伪代码那样修改类的每个单独实例的属性中的数据:

internal class Core {
async void Tick() {
while (isRunning) {
foreach (var gameObject in gameObjects) {
// Get attribute information
var refToAttribute = gameObject.... // Somehow get information
if (!refToAttribute.Initialized) {
// Do some stuff
refToAttribute.Initialized = true;
}
}
await Task.Delay(1);
}
}
}

编辑

当来自TypeScript世界时,我可以在创建类时返回一个新的类实例:

export function GameObject() {
return function (constructor: T) {
return class extends constructor {
initialized = false;
}
}
}
@GameObject
export class Player {
}

那么现在,在我的循环中,我可以访问instance,但是Player没有访问权

现在,在这个类中,是否可以为该类的每个单独实例修改属性中的数据

不,属性附加到,而不是该类的实例。该属性只有一个实例,并且该实例附加到类Player。您可以从播放器实例访问属性,但只能通过查看附加到类型的属性。所以你不能用它来为任何特定的玩家实例提供额外的信息。

在静态类型语言中可以做的是包装值。像这样的代码可以实现您想要做的事情:

public class PlayerGameObject
{
public bool IsInitialized { get; set; }
public Player Player { get; set; }
}
// …
foreach (var gameObject in gameObjects)
{
if (!gameObject.IsInitialized)
{
var player = gameObject.Player;
// do some stuff
gameObject.IsInitialized = true;
}
}

是否可以将信息存储在与类实例相关的属性中?

。属性是类定义的一部分,而不是类的实例。这是不可能的,同样的原因,一个方法不能对一个类的一个实例是公共的,而对同一个类的另一个实例是私有的。

关于类实例的信息只能存储在它的字段和属性中。

我建议您使用基类。

//Your framework
abstract class GameObject
{
internal bool Initialized { get; set; } = false;
}

//Inside program that uses the framework
class Player : GameObject
{
}

现在Player类有一个只有你的代码可以访问的属性。

//Your framework
void Initialize(GameObject obj)
{
if (!obj.Initialized)
{
//Do something
obj.Initialized = true;
}
}
//Inside program that uses the framework
var player = new Player();
if (player.Initialized) //Compile-time error