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

后端 未结 3 637
难免孤独
难免孤独 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 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 value, String key)
        {
            Session[key] = value;
        }
    
        public T retrieve(String key) where T:class
        {
            return  Session[key] as T ;
        }
    

提交回复
热议问题