C Sharp Object 在另一个类中仅创建和引用 1 个对象

发布于 2024-12-08 08:36:29 字数 1398 浏览 0 评论 0原文

我需要在商店场景应用程序中实现 1..* 和 1..1 关系。(类:Member、Order、OrderLine、Product、Program、User) 我如何处理只有 1 个订单的 1 个用户许多 OrderLines(最好使用列表结构?

这是我的用户类:

namespace ConsoleApplication1
{
    public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
        public User() {}

        //Overrides
        public override bool Equals(object obj)
        {
            return obj.ToString() == this.ToString();
        }
        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }
        public override string ToString()
        {
            string myUser;
            myUser = string.Format("First Name: {0}; Last Name: {1}", fName, lName);
            return myUser;     
        }

        // Properties
        public string fName
        {
            get
            {
                return ffName;
            }
            set
            {
                ffName = value;
            }
        }
        public string lName
        {
            get
            {
                return llName;
            }
            set
            {
                llName = value;
            }
        } 
    }
}

I need to implement 1..* and 1..1 relationships in a store scenario application.(Classes: Member, Order, OrderLine, Product, Program, User) How do i go about a 1 user only having 1 Order that can have many OrderLines (preferably using a List structure?

This is my User class:

namespace ConsoleApplication1
{
    public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
        public User() {}

        //Overrides
        public override bool Equals(object obj)
        {
            return obj.ToString() == this.ToString();
        }
        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }
        public override string ToString()
        {
            string myUser;
            myUser = string.Format("First Name: {0}; Last Name: {1}", fName, lName);
            return myUser;     
        }

        // Properties
        public string fName
        {
            get
            {
                return ffName;
            }
            set
            {
                ffName = value;
            }
        }
        public string lName
        {
            get
            {
                return llName;
            }
            set
            {
                llName = value;
            }
        } 
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

南城追梦 2024-12-15 08:36:29

您可以有一个 Order 类和一个 OrderLine 类。 Order 类将有一个 OrderLines 列表,而 User 类可以有一个 Order 成员。

像这样的东西:

public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;
        private Order order = null;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
...
}

public class Order
{
 List<OrderLine> orderLines = null;
}

public class OrderLine
{
}

You can have an Order class and an OrderLine class. The Order class will have a List of OrderLines and the User class can have a Order member.

Something like:

public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;
        private Order order = null;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
...
}

public class Order
{
 List<OrderLine> orderLines = null;
}

public class OrderLine
{
}
梦一生花开无言 2024-12-15 08:36:29

您必须将 OrderOrderLine 类实现为:

class OrderLine
{
      //some code
}


class Order
{
     List<OrderLine> lstOrderLine;

     //some code
}

然后将 Order 类添加到您的用户类中。

You have to implement the Order and the OrderLine class as:

class OrderLine
{
      //some code
}


class Order
{
     List<OrderLine> lstOrderLine;

     //some code
}

Then add the Order class to your user class.

多孤肩上扛 2024-12-15 08:36:29

编辑:删除尖刻和态度:)

首先你需要一个命令(暗示你需要为此上课)。现在需要将订单附加到用户。因此添加一个 User 类型的字段。这样就可以处理一个用户的一个订单。 (请注意,一个用户可以下多个订单)

所以现在您的订单缺少行。添加另一个成员变量,它是线类型列表。现在,您需要在订单中添加添加、删除和查询订单行的方法。

编辑:提出了“添加字段”的含义的问题。添加字段意味着添加属性或私有成员。当你这样做时,你正在做组合的技术术语。组合通常被解释为“具有”关系。因此,订单“有一个用户”和“有一个订单行列表”

Class User()
{
    public string firstName { get; set; }
    public string lastName {get; set; }
    public int id { get; set;}
}

Class OrderLine()
{

}

Class Order()
{
    private List<OrderLine> orderLines;
    public User submitter { get; set;}

    public Order()
    {
         orderLines = new List<OrderLine>();
    }

    public void AddOrderLine(OrderLine newOrderLine)
    {
         this.orderLines.Add(newOrderLine);
    }

    public IList<OrderLine> GetOrderLines()
    { 
         return this.orderLines;
    }
}

示例

User customer1 = new User();
// Initialize customer1 values...
Order someOrder = new Order();
someOrder.submitter = customer1;
someOrder.AddOrderLine(new OrderLine());

编辑:将成员类更改为用户类

Edit: Removed snarkyness and attitude :)

First you need an order (hint you are going to need a class for that). Now the order needs to be attched to a user. So add a field of type User. That takes care of one order one user. (Note that a user can make more than one order)

So now you order is missing lines. Add another member variable that is a list of line types. Now in your order you need to add methods to add, remove and query order lines.

Edit: The question was raised what was meant by "add a field". Add a field means add a property or private member. When you are doing this you are doing the technical term of composition. Composition is commonly explained as a "has a" relationship. So an order "has a user" and "has a list of order lines"

Class User()
{
    public string firstName { get; set; }
    public string lastName {get; set; }
    public int id { get; set;}
}

Class OrderLine()
{

}

Class Order()
{
    private List<OrderLine> orderLines;
    public User submitter { get; set;}

    public Order()
    {
         orderLines = new List<OrderLine>();
    }

    public void AddOrderLine(OrderLine newOrderLine)
    {
         this.orderLines.Add(newOrderLine);
    }

    public IList<OrderLine> GetOrderLines()
    { 
         return this.orderLines;
    }
}

Example

User customer1 = new User();
// Initialize customer1 values...
Order someOrder = new Order();
someOrder.submitter = customer1;
someOrder.AddOrderLine(new OrderLine());

EDIT: Changed Member class to User class

请爱~陌生人 2024-12-15 08:36:29

您最近的评论澄清了您的问题:

创建每一个并不难,我只是不明白如何让关系与 1..* 或 1..1 一起工作。如果我创建一个订单,我总是可以创建另一个订单

所以,让我们来谈谈关系的类型。

关系类型

关系类型并不涉及系统中实体的绝对数量。他们只是谈论与其他实体相关的实体数量。

1:1 关系

这意味着两种实体类型必须成对存在。如果存在一个 A 类型实体,则只能存在一个 B 类型实体。例如,您的用户订单。没有用户就不可能存在订单,并且用户只能有一个订单。这并不意味着只有一个用户 - 可能有 42 个用户。这只是意味着,如果存在 Order,则 User 也必须存在,并且 User 只能有一个 Order.

有一个严格的和不太严格的版本。从技术上讲,我只是描述了 1:{0 或 1} 关系。在真正的 1:1 关系中,如果用户存在,您要求订单也存在。如果另一个不存在,则两者都不可能存在。然而,在谈论关系数据库时,这一约束通常会被放松(但仅限于一个方向 - 在这种情况下,如果没有 User,您仍然无法拥有 Order)。

您可以使用如下代码来建模这种关系:

public class User
{
    public Order Order { get; set; }
}

public class Order
{
    // You could put a reference here back to the User if you want...
}

请注意,仅支持 User 的一个 Order 有点奇怪。将其设为 1:* 更有意义。但如果这是您的作业的要求,那么这就是您对其进行建模的方式。

1:* 关系

这类似于 1:1 关系。但它放宽了一些限制,因此如果存在 A 类型的实体,则可以存在任意数量(包括零)的 B 类型实体。该示例是 OrderOrderLine。同样,对于任一实体类型的存在数量没有限制。 系统中可能有 57 个订单。如果没有 Order,就不可能有 OrderLine,并且每个 Order 可能有多个 OrderLine

您可以使用如下代码来建模这种关系:

public class Order
{
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    // You could put a reference here back to the Order if you want...
}

在代码中强制执行关系概念

我不能代表您的作业,因此请确保您根据您的作业要求支持我在这里所说的内容。

您不应该尝试在代码中强制诸如此类的基本关系概念。数据库在这方面做得更好,有更好的(声明性)语言来描述关系,并且将成为系统的最终数据源。

相反,您应该只创建一个遵循关系的软模型(如上面的代码示例所示),并让数据库对这些约束进行真正的监管。

示例:

  • 您不应尝试限制代码中 Order 类型的构造,也不应要求存在 User 来构造 Order (作为代码实体)。
  • 您不应要求存在 Order 才能创建 OrderLine(作为代码实体)。

尝试在代码中加入这些限制不会给你带来任何好处。当您将实体持久保存到数据库时,数据库将为您确保这些关系(假设您已正确设置它,您将学习如何做到这一点)。您的错误将被发现,并且您将很快养成避免此类错误的习惯。

试图在代码中加入这些限制会伤害你。编写程序将会更加困难,为代码编写单元测试也会更加困难。

例如,考虑比较 OrderLine 值的算法或测试。也许您希望将其与假设 OrderLine 进行比较。如果您的代码中存在关系限制,则还必须创建假设的 OrderUser。您还会将假设的 UserOrder 与真实情况进行比较吗?如果您的算法不应该关心它源自哪个UserOrder 怎么办?如果您不打算比较它们,为什么要费心去创建它们呢?

所以:不用担心。对您的关系进行软建模,以便轻松在对象之间导航,并让数据库为您进行严格的关系验证。

Your most recent comment cleared up your question:

Its not hard to create each one i just dont understand how to get the relationship to work with 1..* or 1..1. If i create an Order i can always create another order

So, let's talk about the types of relationships.

Relationship types

Relationship types don't talk about absolute numbers of entities in the system. They just talk about numbers of entities in relation to other entities.

1:1 Relationship

This means that the two entity types must exist in pairs. If one entity of type A exists, then only one entity of type B can exist. For example, your User and Order. An order can't exist without a User, and a User can only have one Order. This doesn't mean there is only one User - there could be 42 users. This just means that if an Order exists, a User must also exist, and that the User can only have one Order.

There is a strict and less strict version of this. Technically, I just described something like a 1:{0 or 1} relationship. In a real 1:1 relationship you would require that the Order exists if the User exists. Neither could exist if the other didn't exist. However this constraint is usually relaxed when talking about relational databases (but only in one direction - in this case you still can't have an Order without a User).

You can model this relationship with code like this:

public class User
{
    public Order Order { get; set; }
}

public class Order
{
    // You could put a reference here back to the User if you want...
}

Note that it is a bit weird to only support only one Order for a User. It makes more sense to make it 1:*. But if that is a requirement of your assignment, then this is how you'd model it.

1:* Relationship

This is similar to the 1:1 relationship. But it relaxes some of the restrictions so that if an entity of type A exists, then any number (including zero) of type B can exist. The example is the Order and OrderLine. Again, there is no restriction on how many of either entity type exist. There could be 57 orders in the system. You just can't have an OrderLine without an Order, and there could be multiple OrderLines per Order.

You can model this relationship with code like this:

public class Order
{
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    // You could put a reference here back to the Order if you want...
}

Enforcing relational concepts in code

I can't speak for your assignment, so make sure you back up what I am saying here against what your assignment requires.

You should not try to enforce basic relational concepts like these in code. The database is better at it, has better (declarative) language to describe the relationships, and is going to be your ultimate source of data for the system.

Instead, you should just do a soft model that follows the relationships (as the code samples above do), and let the database do the real policing of those constraints.

Examples:

  • You should not try to restrict construction of Order types in code, and you shouldn't require a User to exist to construct an Order (as code entities).
  • You should not require an Order to exist to create an OrderLine (as code entities).

Trying to put these sorts of restrictions in code buys you nothing. When you persist the entities to the database, the database will ensure these relationships for you (assuming you've set it up correctly, which you will learn to do). Your error will be caught, and you'll learn habits that avoid these types of errors very quickly.

Trying to put these sorts of restrictions in code hurts you. It will be harder to write your program, and it will be harder to write unit tests for your code.

For example, consider an algorithm or test that compares OrderLine values. Maybe you want it to compare to a hypothetical OrderLine. If you had relational restrictions in place in your code, you'd also have to create a hypothetical Order and User. Would you also compare the hypothetical User and Order to the real ones? What if your algorithm shouldn't care what User or Order it originated from? If you're not going to compare them, why bother creating them to begin with?

So: Don't worry about it. Softly model your relationships so that it is easy to navigate between your objects, and let the database do your strict relationship validations for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文