嵌套类可以访问它嵌套的类的哪些字段? [英] What fields can a nested class access of the class it's nested in?
问题描述
我在 C# 中有一个 Web 服务,并且想要一个嵌套的内部类,它抽象出会话集合,如下所示:
<前><代码>公共类服务:System.Web.Services.WebService{[网络方法]公共字符串 Foo(字符串票){SessionPool.getSession(ticket);}私有类会话池{公共静态会话 getSession(字符串票){//这就是我想要做的,但我无法访问 Context返回 (Session)Context.Session[ticket];}}}是否可以通过嵌套类访问 WebService 类的 HTTP 上下文?如果没有,有没有办法存储对它的引用?
C# 中的嵌套类与 Java 中的(非静态)内部类不同.没有对包含类的实例的隐式引用 - 因此您不能在没有显式引用的情况下使用包含类的任何实例成员.
但是,您确实可以访问包含类的所有私有成员 - 使用合适的实例成员引用.
I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this:
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Foo(string ticket)
{
SessionPool.getSession(ticket);
}
private class SessionPool
{
public static Session getSession(string ticket)
{
// this is what i want to do, but I can't access Context
return (Session)Context.Session[ticket];
}
}
}
Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?
Nested classes in C# aren't like (non-static) inner classes in Java. There is no implicit reference to an instance of the containing class - so you can't use any instance members of the containing class without an explicit reference.
However, you do have access to all private members of the containing class - with a suitable reference for instance members.
这篇关于嵌套类可以访问它嵌套的类的哪些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!