2012-04-12 106 views
1

可能重复:
.NET: Determine the type of “this” class in its static method在静态方法中调用非静态GetType()?

你好,有没有办法来调用非静态GetType()在非静态类,而无需使用typeof()

下面是我正在处理的代码示例。

private static ISession GetOrCreate(ISessionFactory factory) 
{ 
    if (HttpContext.Current!=null) 
    { 
     ISession session = GetExistingWebSession(); 
     if (session == null) 
     { 
      session = OpenSessionAndAddToContext(factory); 
     } 
     else if (!session.IsOpen) 
     { 
      session = OpenSessionAndAddToContext(factory); 
     }   return session; 
    } 
} 

private ISession GetExistingWebSession() 
{ 
    return HttpContext.Current.Items[GetType().FullName] as ISession; 
} 
+0

您正在尝试按其类型查找对象,而不知道它的类型。这应该如何工作? – hvd 2012-04-12 09:19:41

+1

为什么你不想使用'typeof'? – Jodrell 2012-04-12 09:21:04

+1

为什么首先使用类型名称作为您的密钥? – Jodrell 2012-04-12 09:23:10

回答

0

不能在静态方法中使用“this”,无论该类是静态的还是非静态的。你为什么不想用typeof?在这种情况下,这是完全合理的,因为您始终知道静态方法中的包含类。使用GetType()的唯一原因是有可能在派生类中调用它。

2

typeof()是一种编译时方法。你称它为特定类型。

GetType()是一种运行时方法。你称它为特定的实例。如果class(type)是静态的,你不能得到它的实例,因此调用该方法。

0

是的,你可以使用GetExistingWebSession来调用GetType方法,因为它是一种非静态方法。

但是你的问题其实是,你不能从内部GetOrCreate

你需要一些方法来创建你的类,然后你可以使用的一个实例调用GetExistingWebSession。

例如

MyClass c=new MyClass(); 
ISession session = c.GetExistingWebSession();