铸造泛型类型"为T"同时实施T的类型 [英] Casting generic type "as T" whilst enforcing the type of T
问题描述
我在这里缺少一个窍门,我认为,不能相信,我从来没有这样做过。但是,我怎么能投用关键词作为一个泛型类型?
[Serializable接口]
公共抽象类是SessionManager< T>其中T:ISessionManager
{ 保护是SessionManager(){} 公共静态ŧ的GetInstance(HttpSessionState会话)
{ //确保有一个会话ID
如果(唯一ID == NULL)
{
。唯一ID = Guid.NewGuid()的ToString();
} //从会话对象
ŧ经理=会话[唯一ID]为T;
如果(经理== NULL)
{
经理= Activator.CreateInstance< T>();
会议[唯一ID] =经理;
} 返回经理; } 保护静态字符串唯一ID = NULL;}
行 T经理=会话[唯一ID]为T;
引发以下错误:
类型参数T不能使用
用为运算符,因为它
没有类类型约束,也不是
类约束
块引用>现在,我想知道这样做的原因;我没有告诉身体编译器T是一个类。如果我更换:
公共抽象类是SessionManager< T>其中T:ISessionManager
与
公共抽象类是SessionManager< T>其中T:类
...然后code成功生成。
但我的问题是这样;我怎么能有既对泛型类和ISessionManager enforcements?我希望有一个为这是一个非常简单的答案。
编辑:
我想补充我曾尝试:其中T:ISessionManager,类
,结果发现我已经无法正确读取我的编译器错误。够简单,只是把类ISessionManager之前
修复该问题。我没有读过错误是:
在'类'或'结构'约束
必须出现在任何其他
约束。
块引用>在阿呆的时刻。
解决方案...其中T:类,ISessionManager
如果你要使用其中
关键字
在这里方法则是使用泛型的例子公共无效店< T>(吨价,串键)
{
会话[关键] =价值;
} 公共ŧ检索< T>(字符串键)其中T:类
{
返回会话[关键]为T;
}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] public abstract class SessionManager<T> where T : ISessionManager { protected SessionManager() { } public static T GetInstance(HttpSessionState session) { // Ensure there is a session Id if (UniqueId == null) { UniqueId = Guid.NewGuid().ToString(); } // Get the object from session T manager = session[UniqueId] as T; if (manager == null) { manager = Activator.CreateInstance<T>(); session[UniqueId] = manager; } return manager; } protected static string UniqueId = null; }
The line
T manager = session[UniqueId] as T;
throws the following error:The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
Now, I think understand the reason for this; I've not physically told the compiler that T is a class. If I replace:
public abstract class SessionManager<T> where T : ISessionManager
with
public abstract class SessionManager<T> where T : class
... then the code builds successfully.
But my question is thus; how can I have both the class and ISessionManager enforcements on the generic type? I'm hoping there's a very simple answer for this.
EDIT: Just to add I had tried:
where T : ISessionManager, class
, turns out I hadn't read my compiler error properly. Simply enough, just putting class beforeISessionManager
fixes the issue. The error I hadn't read was:"The 'class' or 'struct' constraint must come before any other constraints".
Dumb moment over.
解决方案... where T : class, ISessionManager
In case you want to use the where
keyword
on methods here is an example that also uses genericspublic void store<T>(T value, String key) { Session[key] = value; } public T retrieve<T>(String key) where T:class { return Session[key] as T ; }
这篇关于铸造泛型类型&QUOT;为T&QUOT;同时实施T的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!