【问题标题】:Object-oriented programming: Association面向对象编程:关联
【发布时间】:2010-07-31 01:36:21
【问题描述】:

UML中有概念关联所以我想用C#来实现它。

/* 在面向对象的编程中,关联定义了对象类之间的关系,它允许一个对象实例导致另一个对象实例代表它执行操作。这种关系是结构性的,因为它指定一种对象连接到另一种对象 */

你能告诉我我们如何编码对象之间的关联关系吗?

谢谢

【问题讨论】:

  • 参加 www.eliminatecodefear.com 上的“面向对象设计大师”课程 - 在我看来,它是在线学习实用的面向对象设计和开发以及 OOP HW 作业的最佳资源之一,这使得它站出来。 (硬件非常重要,否则你不应该打扰)

标签: c# oop uml


【解决方案1】:

AirConditioner Class 与 RemoteControl Class 相关联的方式是 RemoteControl Class 成为 AirConditioner Class 的属性。所以我们可以说,AirConditioner Class 有一个名为 RemoteControl 的属性,但它本身也是一个完整的 Class。

class AirConditioner
{
    //private members 
    private bool _airConditionerRunning;
    private RemoteControl _myRemote;

    //public method to access the remote
    public RemoteControl returnMyRemote()
    {
        return _myRemote;
    }

    //Rest of properties and methods etc
}

class RemoteControl
{
   //methods and peroperties of remoteControl Class
}

【讨论】:

    【解决方案2】:
    • StackOverFlowUser 类与 StackOverFlowQuestion 类相关联
      • StackOverFlowUser 使StackOverFlowQuestion
    class StackOverFlowUser
    {
        public StackOverFlowQuestion PostQuestion(string title, string msg)
        {
            //some logic
            
            return new StackOverFlowQuestion(title, msg);
        }
    }
    
    class StackOverFlowQuestion
    {
        public StackOverFlowQuestion(string title, string msg)
        {
            //more logic here
        }
    }
    

    【讨论】:

    • 不错。你因为让我发笑而投了赞成票……但你在某处缺少一个右括号。
    • 这不是关联实现的示例。用户和问题之间没有结构关系,只是依赖关系。
    猜你喜欢
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2010-09-18
    • 2023-03-21
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多