-3

我有这个简单的代码:

class ResourceInterceptor: IResourceInterceptor
        {

            public bool OnFilterNavigation(NavigationRequest request)
            {
                return false;
            }

            ResourceResponse IResourceInterceptor.OnRequest(ResourceRequest request)
            {
                request.Referrer = "http://www.google.com";
                return null;
            }
        }

我需要将一个变量传递给类(只需阅读它,不要编辑),但如果我插入一个未在类中声明的变量,它会给我这个错误:

无法通过嵌套类型“WindowsFormsApplication1.Form1.ResourceInterceptor”访问外部类型“WindowsFormsApplication1.Form1”的非静态成员

例如我需要这样的东西(显然不起作用!)

public string referrer = "www.google.com";
class ResourceInterceptor: IResourceInterceptor
        {

            public bool OnFilterNavigation(NavigationRequest request)
            {
                return false;
            }

            ResourceResponse IResourceInterceptor.OnRequest(ResourceRequest request)
            {
                request.Referrer = referrer;
                return null;
            }
        }
4

2 回答 2

4

您可以使用初始化构造函数。例如:

class ResourceInterceptor: IResourceInterceptor
{
    public ResourceInterceptor(string referer)
    {
        m_Referer = referer;
    }

    public bool OnFilterNavigation(NavigationRequest request)
    {
        return false;
    }

    ResourceResponse IResourceInterceptor.OnRequest(ResourceRequest request)
    {
        request.Referrer = m_Referrer;
        return null;
    }

    private string m_Referer;
}

然后在创建类的实例时简单地将引用者传递给构造函数:

ResourceInterceptor interceptor = new ResourceInterceptor("www.google.com");
于 2013-04-18T07:54:26.807 回答
1

另一种解决方案,如果您只需要在所有类实例中使用该变量,则使用 class ( static) 属性:

class ResourceInterceptor : IResourceInterceptor
{
    // Public class property.
    public static string Referer { get; set; }
    ResourceResponse IResourceInterceptor.OnRequest(ResourceRequest request)
    {
        request.Referrer = Referer;
        return null;
    }
}

// Somewhere else...
ResourceInterceptor.Referer = "www.google.com";

在此之后,您的所有ResourceInterceptor实例将共享相同的Referer类属性。

于 2013-04-18T08:04:38.767 回答