C#如何在类实例之间保留数据? [英] C# how can I preserve data between class instances?

查看:100
本文介绍了C#如何在类实例之间保留数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为模糊的标题表示歉意,但我不确定如何进一步解释它.

Apologies for the vague title, but I am not really sure how else to explain it.

赋予A,B和C类.

如果A类包含一个列表,如何保存该列表中的数据,以便B和C类可以访问列表中的数据(即使B和C都新建了自己的A类实例)?

If Class A contains a List, how can I preserve the data in that list so that Class B and C can access the data in the list (even if B and C both new up their own instance of Class A)?

B类和C类必须创建自己的实例(这是我无法控制的.)

Classes B and C must create their own instances (this is out of my control).

我正在使用此类作为对象数据源,并且说我无法修改C类的内容.

I am using this class as my object data source, and let's say I cannot modify the contents of Class C.

以下是一个示例类:

[DataObject]
public class Product
{
    public string Name {get; set;}
    public string Category {get; set;}
    public int ID {get; set;}

    public List<Product> ProductList =
        new List<Product>();

    [DataObjectMethod(DataObjectMethodType.Select)]
    public IEnumerable<Product> GenerateReport()
    {
        return ProductList;
    }

}

推荐答案

使用此处定义的静态值:> https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/static

Use static as defined here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static

然后,您将可以访问类属性而不是实例属性.

Then you will be able to access the class properties instead of instance properties.

这篇关于C#如何在类实例之间保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆