【发布时间】:2011-07-19 14:57:43
【问题描述】:
如何在抽象类中定义的静态方法中获取当前的Type?
请注意,由于方法是在抽象类中定义的,我不能使用typeof。
我为什么要这样做?一个可能的用法是属性。考虑以下示例:
[Identifier(1000)]
public class Rock : Entity { }
public abstract class Entity
{
public static ushort Identifier
{
get
{
// How do I get here the current type of the object?
Type currentType = ...;
// in a non-static method or property, I'd do:
// Type currentType = this.GetType();
foreach (IdentifierAttribute attribute in currentType.GetCustomAttributes(true))
return attribute.Identifier;
throw new EntityException("No identifier has specified for this type of entity.");
}
}
}
Rock rock = new Rock();
// should print 1000
Console.WriteLine(rock.Identifier);
编辑:
这里是场景。
实体表示一个 3D 对象。我正在编写一个服务器软件,其中包含此类实体的列表。服务器手动序列化列表并将其发送给客户端。由于性能在这里非常重要,因此我不会发送类型名称。每种类型的实体都有唯一的标识符,因此当客户端获取数据时,它可以高效地反序列化。
要创建实体的实例,我正在执行以下操作:
Entity entity = EntityRepository.Instance.CreateNew(identifier);
EntityRepository 类如下所示:
public sealed class EntityRepository
{
private static readonly Lazy<EntityRepository> lazy =
new Lazy<EntityRepository>(() => new EntityRepository());
IDictionary<ushort, Func<Entity>> _repo;
private EntityRepository()
{
_repo = new Dictionary<ushort, Func<Entity>>();
}
public static EntityRepository Instance
{
get { return lazy.Value; }
}
public Entity CreateNew(ushort id)
{
return _repo[id]();
}
public void Add<T>(ushort id)
where T : Entity, new()
{
_repo.Add(id, new Func<Entity>(() =>
{
return new T();
}));
}
}
当前的Add<T> 方法有一个代表标识符的参数。
但是我将如何编写一个没有参数的Add<T> 方法 - 自动识别标识符?
所以我在考虑给嵌套的Entity添加一个属性:
[Identifier(1000)]
public class Rock : Entity { }
以及返回Identifier 属性值的静态属性。
然后,没有参数的Add<T> 方法看起来像:
public void Add<T>(ushort id)
where T : Entity, new()
{
_repo.Add(T.Identifier, new Func<Entity>(() =>
{
return new T();
}));
}
请注意,在这种情况下,我可以使用T.GetType() 来获取属性,但这不是重点。我怎样才能在静态属性Entity.Identifier 中做到这一点?
【问题讨论】:
-
Identifier属性和Identifier属性有什么关系? -
我已编辑问题以澄清这一点。
-
您说可以使用
T.GetType()不是“重点”(尽管您实际上的意思是typeof(T))-但是如果这样可以解决您的问题,为什么不使用它呢?您尝试这样做的方式根本行不通 - 所以请使用确实有效的方式。
标签: c# static attributes types