首页 > c# > 如何在C#中创建一个包含数据和get方法的类?

如何在C#中创建一个包含数据和get方法的类? (How to create a class with its data and get method in C#?)

2016-01-25 c#asp.net

问题

我是一名新的C#开发人员,我正在尝试开发一个简单的ASP.NET应用程序。我现在正在努力创建一个包含静态数据和get方法的类。我有永远不会改变的静态数据,我想把它们放在一个包含Properties,Constructors,GetData()方法及其数据的类中。那我该怎么办呢?

我已经尝试过写这个类,但是我仍然面临着GetData()方法的困难,并且用数据填充它。

这是我的C#代码:

public class TestItem
    {
        //Properties
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Url { get; set; }


        // Default Constructor
        public TestItem() { }


        // Constructor
        public TestItem(int id, int parentId, string title, string description, string url)
        {
            Id = id;
            ParentId = parentId;
            Title = title;
            Description = description;
            Url = url;
        }


        // Get Method
        public IEnumerable<TestItem> GetTestItemItems()
        {
            List<TestItem> testItems = new List<TestItem>();
            try
            {
                testItems = (from item in TestItem
                             select item);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return testItems;
        }


    // Populate the Data
        List<TestItem> items = new List<TestItem>
        {
            new TestItem
            {
                Id = 0,
                ParentId = 0,
                Title = "",
                Description = "",
                Url = ""
            },
        };


    }

我现在的问题是使用GetData()方法,因为我在try块中得到一条红线,我不知道为什么。有谁可以帮我解决这个问题?

// Get Method
    public IEnumerable<TestItem> GetTestItemItems()
    {
        List<TestItem> testItems = new List<TestItem>();
        try
        {
            testItems = (from item in TestItem
                         select item);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return testItems;
    }

更新:

感谢@II ARROWS,他试图在这里帮助我。我尝试了他的答案,但是,我仍然收到以下错误:

在此输入图像描述

请注意,我将名称从TestItem更改为SystemMenu和TestItemRepository更改为SystemMenuRepository。我这个类的最终目标是稍后在另一个页面中使用它,我可以将其静态数据作为DataTable获取。我怎样才能做到这一点?

解决方法

我不明白你的代码,你声称你需要一个静态的“数据”,但我没有看到(你的示例代码有一个公共构造函数),GetData方法不是静态的(除了已经指向你的错误)得到一个班而不是你的名单)。

要声明一个静态方法,您应该在public关键字后面使用static关键字,但是您还需要静态数据(或者即时创建),因为您不能依赖该类的实例。

你可能应该使用单例模式,这里有一些参考:

它是什么:https//en.wikipedia.org/wiki/Singleton_pattern

如何实现它:http//csharpindepth.com/Articles/General/Singleton.aspx

简而言之,单例是无法从外部世界实例化的类,调用静态方法(您的GetData)它会在第一次使用私有静态字段调用实例时自动进行实例化。然后,返回数据。

这里有两个类,一个包含元素,另一个包含元素列表(这是一个简单的实现,请参考上面的链接):

public class TestItem
{
    //Properties
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }

    // Constructor
    public TestItem(int id, int parentId, string title, string description, string url)
    {
        Id = id;
        ParentId = parentId;
        Title = title;
        Description = description;
        Url = url;
    }
}



public class TestItemsRepository
{
    private List<TestItem> data;
    private static TestItemsRepository instance;

    private TestItemsRepository()
    {
        //Populate data
        data = new List<TestItem>
        {
            new TestItem
            {
                Id = 0,
                ParentId = 0,
                Title = "",
                Description = "",
                Url = ""
            },
        };
    }

    public static IEnumerable<TestItem> GetTestItems()
    {
        if (instance==null)
        {
             instance = new TestItemsRepository();
        }
        return instance.data;
    }
}

问题

I am a new C# developer and I am trying to develop a simple ASP.NET application. I am struggling now with creating a class with its static data and get method. I have static data that will never be changed and I would like to put them in a class that includes, Properties, Constructors, GetData() method and its data. So how can I do that?

I've tried writing the class but I am still facing difficulty with the GetData() method and with populating it with the data.

Here's my C# code:

public class TestItem
    {
        //Properties
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Url { get; set; }


        // Default Constructor
        public TestItem() { }


        // Constructor
        public TestItem(int id, int parentId, string title, string description, string url)
        {
            Id = id;
            ParentId = parentId;
            Title = title;
            Description = description;
            Url = url;
        }


        // Get Method
        public IEnumerable<TestItem> GetTestItemItems()
        {
            List<TestItem> testItems = new List<TestItem>();
            try
            {
                testItems = (from item in TestItem
                             select item);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return testItems;
        }


    // Populate the Data
        List<TestItem> items = new List<TestItem>
        {
            new TestItem
            {
                Id = 0,
                ParentId = 0,
                Title = "",
                Description = "",
                Url = ""
            },
        };


    }

My problem now is with the GetData() method as I am getting a red line within the try block and I don't know why. Could anyone help me in this matter?

// Get Method
    public IEnumerable<TestItem> GetTestItemItems()
    {
        List<TestItem> testItems = new List<TestItem>();
        try
        {
            testItems = (from item in TestItem
                         select item);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return testItems;
    }

UPDATE:

Thanks to @II ARROWS for his try to help me here. I tried his answer, however, I am still getting an error which is the following:

enter image description here

Please note, I changed the names from TestItem to SystemMenu and TestItemRepository to SystemMenuRepository. My ultimate goal of this class is to use it later in another page where I can get its static data as a DataTable. How can I do that?

解决方法

I don't understand your code, you claim that you need a static "data" but I don't see any (your sample code has a public constructor) and the GetData method is not static (besides the error already pointed to you of getting a class instead of your list).

To declare a static method, you should use the static keyword after the public keyword, but you will need also static data (or making it on the fly), since you cannot rely on instances of the class.

You should probabily use the singleton pattern, here some reference for you:

What is it: https://en.wikipedia.org/wiki/Singleton_pattern

How to implement it: http://csharpindepth.com/Articles/General/Singleton.aspx

In short, a singleton is class that cannot be instantiated from the outside world, calling a static method (your GetData) it istantiates itself the first time it's called keeping track of the instance using a private static field. Then, returns the data.

Here you have two classes, one with your elements and one with the list of those elements (this is a simple implementation, refer to the link above):

public class TestItem
{
    //Properties
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }

    // Constructor
    public TestItem(int id, int parentId, string title, string description, string url)
    {
        Id = id;
        ParentId = parentId;
        Title = title;
        Description = description;
        Url = url;
    }
}



public class TestItemsRepository
{
    private List<TestItem> data;
    private static TestItemsRepository instance;

    private TestItemsRepository()
    {
        //Populate data
        data = new List<TestItem>
        {
            new TestItem
            {
                Id = 0,
                ParentId = 0,
                Title = "",
                Description = "",
                Url = ""
            },
        };
    }

    public static IEnumerable<TestItem> GetTestItems()
    {
        if (instance==null)
        {
             instance = new TestItemsRepository();
        }
        return instance.data;
    }
}
相似信息