简体   繁体   English

如何使这个C#类和方法静态?

[英]How can I make this C# class and method static?

I am a new ASP.NET developer and I am trying to learn Linq-To-Entities. 我是一名新的ASP.NET开发人员,我正在尝试学习Linq-To-Entities。 I am trying to create a static class called Items in my Data Access Layer. 我正在尝试在我的数据访问层中创建一个名为Items的静态类。 This class has a method to retrieve all the records in Items Entity. 此类有一个方法来检索Items Entity中的所有记录。 And then, I will use it for binding the GridView to it. 然后,我将使用它将GridView绑定到它。 The problem is that I got the following error in my getData() method when I make that class as a static class and I don't know why: 问题是当我将该类作为静态类并且我不知道原因时,我在getData()方法中遇到以下错误:

在此输入图像描述

C# Code: C#代码:

public static class Items
{
    //properties
    public int ID { get; set; }
    public string Code { get; set; }
    public int ItemTypeID { get; set; }
    public string Name { get; set; }
    public int StatusID { get; set; }


    public static IEnumerable<Items> getData()
    {
        List<Items> itemsList = new List<Items>();
        using (ItemsDBEntities context = new ItemsDBEntities())
        {
            itemsList = (from item in context.Items
                        select new Items()
                        {
                            ID = item.ID,
                            Code = item.Code,
                            Name = item.Name,
                            StatusID = item.StatusID
                        }).ToList();
        }
        return itemsList;
    }

Could you please tell me how to fix this error? 你能告诉我如何解决这个错误吗?

Could you please tell me how to fix this error? 你能告诉我如何解决这个错误吗?

//public static class Items
public class Items
{
}

There are clear reasons why Items should not be static . Items不应该是static有明显的原因。

The getData() method can remain static, although that doesn't seem necessary or useful either. getData()方法可以保持静态,尽管这似乎不是必需或有用的。 It just makes testing a little harder. 它只是让测试变得更难。 Do research state-management and the use of static in ASP.NET. 在ASP.NET中研究状态管理和静态的使用。

  • do ask yourself why you think it needs to be static. 要问问自己为什么你认为它需要是静态的。
  • anything with Id and Name properties is an Item , not an Items . 具有IdName属性的任何内容都是Item ,而不是Items
  • in C# we capitalize methods, GetData() . 在C#中我们使用方法GetData()

只需删除Items类的静态声明即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM