Casting generic type “as T” whilst enforcing the type of T

后端 未结 3 636
难免孤独
难免孤独 2021-02-12 12:17

I\'m missing a trick here I think and can\'t believe I\'ve never done this before. However, how can I cast a generic type using the as keyword?

[Serializable]
pu         


        
相关标签:
3条回答
  • 2021-02-12 12:47
    where T : class, ISessionManager
    

    you can go even further

    where T : class, ISessionManager, new()
    

    this will force non abstract class with parameterless ctor to be handed in as T

    0 讨论(0)
  • 2021-02-12 12:55

    Read up on Constraints on Type Parameters in C#.

    In this particular case, you must ensure that T is a class:

    public abstract class SessionManager<T>
        where T : class, ISessionManager
    
    0 讨论(0)
  • 2021-02-12 13:00
    ... where T : class, ISessionManager
    

    In case you want to use the where keyword on methods here is an example that also uses generics

        public void store<T>(T value, String key)
        {
            Session[key] = value;
        }
    
        public T retrieve<T>(String key) where T:class
        {
            return  Session[key] as T ;
        }
    
    0 讨论(0)
提交回复
热议问题