如何在c#中将class的静态变量作为参数传递

时间:2018-01-05 12:23:00

标签: c# class properties static

我正在尝试访问c#中特定inbulit类的属性,但我没有得到如何传递类静态变量并将其作为参数传递给方法。

这是我想要作为参数传递的类:

public class PageSize
{
    //
    public static readonly Rectangle A0;
    //
    public static readonly Rectangle A1;
}

现在我有方法,我希望将上述类的变量作为参数传递,如下所示:

public void NewExportToPDFforLetter(StringWriter sw, string FileName, PageSize s )
{
    //s = new PageSize();
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(s.A0, 30f, 30f, 30f, 30f);
}

我在s.A0收到错误。任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:2)

  

现在我有方法,我希望将上述类的变量作为参数传递,如下所示:public void NewExportToPDFforLetter(StringWriter sw, string FileName, PageSize s )

你为什么要那样做? PageSize内的NewExportToPDFforLetter 已经可以访问,而无需将其作为参数传递:

public void NewExportToPDFforLetter(
    StringWriter sw, 
    string FileName)
{
      var a0 = PageSize.A0; //accesible as long as `Page` is accesible:
                            //public class, internal in same assembly, etc.

      //...
}

如果PageSize无法从NewExportToPDFforLetter实施的任何地方访问,那么您将无法将其作为参数传递开始,因此您正在考虑的选项根本就是不必要的

答案 1 :(得分:1)

如果您希望将属性保持为静态,可以使用PageSize.A0PageSize.A1直接访问它们。

如果要从实例访问它们,则必须删除属性的静态声明。

答案 2 :(得分:1)

由于静态类变量不是实例的一部分,因此不应使用instance.property语法,而应使用classname.property。

因此改变

Document pdfDoc = new Document(s.A0, 30f, 30f, 30f, 30f);

Document pdfDoc = new Document(PageSize.A0, 30f, 30f, 30f, 30f);

然而,它不可见,但可能你不想使用静态。在这种情况下,您必须通过更改

来删除静态,而不是上述更改
public static readonly Rectangle A0;
//
public static readonly Rectangle A1;

public readonly Rectangle A0;
//
public readonly Rectangle A1;

答案 3 :(得分:0)

您需要使用new NetworkRequest().execute(API_URL); 代替PageSize.A0

访问A0

答案 4 :(得分:0)

这是你可以这样做的方式

var size= PageSize.A4;
NewExportToPDFforLetter(stringWriter, "Application Approval Letter", HttpContext.Current.Response,(Rectangle)size);

public void NewExportToPDFforLetter(StringWriter sw, string FileName, HttpResponse Response, Rectangle s )
{
    Document pdfDoc = new Document(s, 30f, 30f, 30f, 30f);
}