首页 \ 问答 \ 封装和接口(Encapsulation and Interfaces)

封装和接口(Encapsulation and Interfaces)

几天后,我一直在微软网站上的.NET教程中研究和学习这一特定课程。 链接

正如您可能已经知道,每节课结束时都会有“作业”。 这次我应该使用一些新功能升级给定项目并实现Encapsulation和Interfaces。

新功能应包括:

  • 客户拥有揭露其历史订单的房产

    //更新:已实施

  • 客户公开了添加订单的方法

  • 尝试添加空订单应该什么都不做

  • 尝试使用现有OrderNumber添加订单应替换现有订单(不添加重复)

    //我唯一成功的就是删除之前使用相同名称的“订单”,而不是仅仅替换它。

  • 订单应该公开OrderDate(可以读/写)

  • 尝试在将来添加订单和OrderDate应该什么都不做

我确实设法添加了大部分功能。 我的项目目前( 更新 ):

namespace ConsoleApp2
{
class Program
{
    static void Main()
    {
        Customer customer1 = new Customer("John");
        Customer customer2 = new Customer("George");
        var customers = new List<Customer>() { customer1, customer2 };
        customer1.AddOrder("car", "12/7/1999"); // will be removed due to same name
        customer1.AddOrder("vase", "20/6/2024");// will not be added to the list because of the future time
        customer1.AddOrder("car", "3/12/2014");
        customer1.AddOrder("headphones", "3/12/2022");// will not be added to the list because of the future time
        customer2.AddOrder("headphones", "10/3/2002");
        customer2.AddOrder("", "");// will not be added to the list due to empty values

        //print customers

        foreach (var customer in customers)
        {
            customer.Print();
        }
    }
}
public class Customer
{
    public string Name { get; }
    private List<Order> orders = new List<Order>();
    private List<Order> ordersHistory = new List<Order>();


    public Customer(string name)
    {
        Name = name;
    }

    public void AddOrder(string name, string date)
    {
        if (name == null) { return; }
        else if (name == "" || date == "") { return; }
        else
        {
            AddHistoricOrder(name, date);
            AddRegularOrder(name, date);
        }


    }
    public void Print()
    {
        Console.WriteLine(Name);
        Console.Write("Orders: ");
        orders.ForEach(Console.Write);
        Console.WriteLine();
        Console.Write("Historic Orders: ");
        ordersHistory.ForEach(Console.Write);
        Console.WriteLine();
        Console.WriteLine($"Order Count: {orders.Count}");
        Console.WriteLine();
        Console.WriteLine();
    }

    private void AddRegularOrder(string name, string date)
    {

        if (DateTime.Parse(date) > DateTime.Now) { return; }
        else
        {

            for (int i = 0; i < orders.Count; i++)
            {
                if (orders[i].OrderName == name)
                {
                    orders.RemoveAt(i);
                }
            }
            orders.Add(new Order(name, date));

        }
    }
    private void AddHistoricOrder(string name, string date)
    {
        ordersHistory.Add(new Order(name, date));
    }
    public override string ToString()
    {
        return $"{Name}";
    }

}
public class Order
{
    public string OrderName { get; }
    public DateTime OrderDate { get; set; }

    public Order(string orderName, string date)
    {
        OrderName = orderName;
        OrderDate = DateTime.Parse(date);;
    }
    public override string ToString()
    {
        return $"{OrderName} ({OrderDate.ToShortDateString()}), ";
    }
}
}

即使我搜索和观看各种视频的封装和接口,我仍然不确定我应该如何在这里实现它们。 你能帮我提高代码效率吗?

我没有实现暴露历史订单的属性(我只是不确定应该做什么)

另外,我并没有真正理解“New is Glue”这一课程的一部分,它说我们应该避免在我们的代码中添加新的关键字,并展示一些使用接口的例子。 我没有找到给定LINK之外的任何信息我想如何避免在这个特定项目中创建新实例? 提前致谢!


For a few days now I've been researching and studying about this particular lesson at .NET tutorials located at the Microsoft site. LINK

As you already may know there is a "homework" at the end of each lesson. This time I should upgrade the given project with some of the new features and implement Encapsulation and Interfaces.

New features should include:

  • Customers have a property exposing their historic Orders

    // update: implemented

  • Customers expose a method for adding an Order

  • Trying to add a null Order should do nothing

  • Trying to add an Order with an existing OrderNumber should replace the existing Order (not add a duplicate)

    // the only thing I succeeded is removing the previous "orders" with the same name instead of just replacing it.

  • Orders should expose an OrderDate (which can be read/write)

  • Trying to add an order with an OrderDate in the future should do nothing

I did manage to add most of these features. My project currently(updated):

namespace ConsoleApp2
{
class Program
{
    static void Main()
    {
        Customer customer1 = new Customer("John");
        Customer customer2 = new Customer("George");
        var customers = new List<Customer>() { customer1, customer2 };
        customer1.AddOrder("car", "12/7/1999"); // will be removed due to same name
        customer1.AddOrder("vase", "20/6/2024");// will not be added to the list because of the future time
        customer1.AddOrder("car", "3/12/2014");
        customer1.AddOrder("headphones", "3/12/2022");// will not be added to the list because of the future time
        customer2.AddOrder("headphones", "10/3/2002");
        customer2.AddOrder("", "");// will not be added to the list due to empty values

        //print customers

        foreach (var customer in customers)
        {
            customer.Print();
        }
    }
}
public class Customer
{
    public string Name { get; }
    private List<Order> orders = new List<Order>();
    private List<Order> ordersHistory = new List<Order>();


    public Customer(string name)
    {
        Name = name;
    }

    public void AddOrder(string name, string date)
    {
        if (name == null) { return; }
        else if (name == "" || date == "") { return; }
        else
        {
            AddHistoricOrder(name, date);
            AddRegularOrder(name, date);
        }


    }
    public void Print()
    {
        Console.WriteLine(Name);
        Console.Write("Orders: ");
        orders.ForEach(Console.Write);
        Console.WriteLine();
        Console.Write("Historic Orders: ");
        ordersHistory.ForEach(Console.Write);
        Console.WriteLine();
        Console.WriteLine($"Order Count: {orders.Count}");
        Console.WriteLine();
        Console.WriteLine();
    }

    private void AddRegularOrder(string name, string date)
    {

        if (DateTime.Parse(date) > DateTime.Now) { return; }
        else
        {

            for (int i = 0; i < orders.Count; i++)
            {
                if (orders[i].OrderName == name)
                {
                    orders.RemoveAt(i);
                }
            }
            orders.Add(new Order(name, date));

        }
    }
    private void AddHistoricOrder(string name, string date)
    {
        ordersHistory.Add(new Order(name, date));
    }
    public override string ToString()
    {
        return $"{Name}";
    }

}
public class Order
{
    public string OrderName { get; }
    public DateTime OrderDate { get; set; }

    public Order(string orderName, string date)
    {
        OrderName = orderName;
        OrderDate = DateTime.Parse(date);;
    }
    public override string ToString()
    {
        return $"{OrderName} ({OrderDate.ToShortDateString()}), ";
    }
}
}

Even tho I searched and watched various videos for encapsulation and interfaces I'm still not sure how should I implement those in here. Could you help me making my code more efficient ?

I did not implement a property for exposing historic Orders (I'm just not sure what that is supposed to do)

Also I did not really understand one part of the lesson called "New is Glue" which says we should avoid adding new keyword to our code and showed some example using interfaces. I failed to find any info outside of the given LINK How am I suppose to avoid creating new instances in this particular project? Thanks in advance!


原文:https://stackoverflow.com/questions/44505752
更新时间:2023-09-18 18:09

最满意答案

如果在Stream模型中使用Tire::Model::Callbacks模块,则应自动删除它。

如果你想从控制器手动运行它代码应该可行。

@stream.destroy
@stream.tire.update_index

If you use Tire::Model::Callbacks module in your Stream model it should be deleted automatically.

If you want to run it manually from controller following code should probably work.

@stream.destroy
@stream.tire.update_index

相关问答

更多
  • 您是否将这些分析仪应用于任何领域? 您在该字段上搜索,还是在_all字段上搜索? 如果您打算将这些分析器用作整个索引的默认分析器,则应将它们命名为default_index和default_search 。 实际上它们都是相同的,因此您可以将分析器指定为default 。 这就是Elasticsearch如何确定在索引时使用哪个分析器: index_analyzer在字段映射中定义,否则 在字段映射中定义的analyzer ,否则 否则,分析器在文档的_analyzer字段中定义 type的默认index_ ...
  • Elasticsearch不会立即为其索引写入更新,它的刷新间隔默认为1秒,因此如果写入和读取发生在1秒以内,那么这可能是导致问题的原因。 您可以降低刷新间隔(我不建议这样做)或只是在控制器中写入Elasticsearch后调用刷新 Tire.index("whatever").refresh Elasticsearch doesn't write updates to its index immediately, it has a refresh-interval that defaults to 1 ...
  • 我意识到这是一个疯狂的迟到的答案,但嘿,这里。 Rspec正在进行直接比较。 它有一个集合,它试图将它与数组进行比较。 但是,Tire将数组定义为不实际返回数组(为什么,我不确定,听起来很烦我!) 鉴于你不打算比较数组,我快速浏览了Collection的来源: https : //github.com/karmi/tire/blob/master/lib/tire/results/collection.rb 好吧,我们没有一个有用的to_ary ......但我们确实有一个,并且包含了Enumerable。 ...
  • 提出这样的问题通常会产生如下答案:RTFM! 如果你看一下轮胎的文件(现在退休),有以下例子: s = Tire.search 'articles' do query do string 'title:T*' end filter :terms, :tags => ['ruby'] sort { by :title, 'desc' } facet 'global-tags', :global => true do terms :tags end facet ...
  • 你可以这样做 should { terms :author, [params[:author]]} if params[:author].present? 要么 should { term :author, params[:author]} if params[:author].present? 要么 should { string "author:#{params[:author]}"} if params[:author].present? You can do like this should ...
  • 如果在Stream模型中使用Tire::Model::Callbacks模块,则应自动删除它。 如果你想从控制器手动运行它代码应该可行。 @stream.destroy @stream.tire.update_index If you use Tire::Model::Callbacks module in your Stream model it should be deleted automatically. If you want to run it manually from controller ...
  • 据我所知,它有一些过滤器,删除字母“a”。 我重写方法,返回我的第一个字母,所以我的新输出是“a_letter”,“b_letter”等,它对我有用。 谢谢@Shadwell的帮助。 As I understood, it had some filter which is removing the letter "a". I rewrite method, that returns my first letters, so my new output was "a_letter", "b_letter" e ...
  • 您可以使用, def browse @search_items = Tire.search(['posts_index', 'channels_index'],{load: true}) do |search| search.query do |q| q.string params[:query], default_operator: "AND" if params[:query].present? end ...
  • 轮胎与例如不同。 思考Sphinx,因为实际上没有发生delta索引:当你的模型发生变化,并且你已经包含了索引回调时,序列化为JSON的整个记录被发送到elasticsearch,替换旧文档(记住elasticsearch实际上是一个“可搜索的文档数据库“)。 如果要从子模型触发父模型中的回调,则必须使用Rails来执行此操作: class Brake < ActiveRecord::Base belongs_to :car, :touch => true end 请参阅ActiveRecord #t ...
  • 您可以启动代码存在的ruby控制台并在那里运行它。 基于模型的轮胎方法的索引名称采用复数形式的模型名称作为索引名称。 例如:article.rb将文章作为索引名称。 Tire.index("").delete 在你的情况下,它会 Tire.index("tags").delete 请注意,您还可以在索引名称中使用通配符 Tire.index("*articles").delete 将删除任何索引名称以“文章”结尾的索引 You can start the ruby consol ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。