引用另一个文件中定义的类?

时间:2018-02-07 22:18:59

标签: c#

我在“Datasource.cs”文件中定义了一个类。在我的另一个asp.net文件“FineUIGrid.aspx.cs”中,我需要引用我在Datasource.cs中定义的类方法。但是当我引用该方法时,会出现错误“当前上下文中不存在名称'class1'”。怎么能解决这个问题? Datasource.cs代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace FineUI.Examples
{

    public class Class1
    {
        public Class1()
        {
        }
       public string write() 
        { 
            string AD = "This is a FineUI DataGrid Example";
            return AD;
         }
     }
}

FineUIGrid.aspx.cs代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace FineUIProject
{

    protected void page_load(object sender, EventArgs e) 
    {
        string information = Class1.write();
     }
}

2 个答案:

答案 0 :(得分:1)

您需要在FineUIProject中添加对FineUI的引用,然后在下面包含using语句。之后,您需要实例化class1并在instanciated对象上调用它

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Text;
    using FineUI.Examples;

    namespace FineUIProject
    {

        protected void page_load(object sender, EventArgs e) 
        {
            Class1 classOne = new Class1();
            string information = classOne.write();
         }
    }

答案 1 :(得分:1)

实例化类或使方法静态。

实例化:

var class = new Class1();
var information = class.write();

静态:

//Class1
public static string write() 
{ 
  string AD = "This is a FineUI DataGrid Example";
  return AD;
}

// no change
string information = Class1.write();

由于Class1用于返回结果的成员变量没有被使用,因此static方法很可能是最好的做法。您可能需要阅读C# static vs instance methods