How can I get the current Type in a static method that is defined in an abstract class?
Note that since the method is defined in an abstract class, I cannot use typeof .
Why do I want to do this? Possible use of attributes. Consider the following example:
[Identifier(1000)] public class Rock : Entity { } public abstract class Entity { public static ushort Identifier { get {
EDIT:
Here is the script.
Entity is a three-dimensional object. I am writing server software that has a list of such objects. The server manually serializes the list and sends it to the client. Since performance is very important here, I am not sending a type name. Each entity type has a unique identifier, so when a client receives data, it can effectively deserialize it.
To create an instance of an object, I do something like:
Entity entity = EntityRepository.Instance.CreateNew(identifier);
The EntityRepository class is as follows:
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(); })); } }
The current Add<T> method has a parameter that represents the identifier.
But how would I write an Add<T> method that has no parameters - that automatically recognizes the identifier?
So, I was thinking about adding an attribute to a nested Entity :
[Identifier(1000)] public class Rock : Entity { }
and a static property that returns the value of the Identifier attribute.
Then the Add<T> method without parameters will look something like this:
public void Add<T>(ushort id) where T : Entity, new() { _repo.Add(T.Identifier, new Func<Entity>(() => { return new T(); })); }
Note that in this case, I could just do T.GetType() to get the attribute, but that is not the point. How to do this in a static property, Entity.Identifier ?