如何将变量传递给c#中的类

时间:2013-04-18 07:50:15

标签: c# class variables

我有这个简单的代码:

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'通过嵌套类型   'WindowsFormsApplication1.Form1.ResourceInterceptor'

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

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;
            }
        }

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

另一种解决方案,如果你只需要在所有类实例中使用该变量,那就是使用类(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类属性。