首页 \ 问答 \ 在TypeScript中获取并设置(get and set in TypeScript)

在TypeScript中获取并设置(get and set in TypeScript)

我正在为一个属性创建get和set方法:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

什么是关键字设置值?


I'm trying to create get and set method for a property:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

What's the keyword to set a value?


原文:https://stackoverflow.com/questions/12827266
更新时间:2023-02-09 11:02

最满意答案

通常采用许多不同的选项/方法:

  1. 阻止就像您展示的API一样。 这是一个非常简单的API,并且仍然可以通过从多线程应用程序中调用API来实现并行性。

  2. 在异步操作中接收/注册处理程序 。 这有时与阻塞API一起提供(事实上,可以简单地通过生成后台线程然后在最后调用处理程序来实现阻塞API)。

  3. 返回FutureListenableFuture对象,这使得界面更具惯用性(通过在返回类型位置返回数据),但表示最终结果,而不是立即可用的结果。 然后可以使用Future来阻止或阻止。

就个人而言,我的推荐是:

interface EmployeeDatabase {
   interface StringWhereClause {
     ListQueryBuilder is(String value);
     ListQueryBuilder contains(String value);
     ListQueryBUilder matchesRegex(String regex);
   }

   interface IntWhereClause {
     ListQueryBuilder is(int value);
     ListQueryBuilder isInRange(int min, int max);
     ListQueryBuilder isGreaterThan(int value);
     ListQueryBUilder isLessThan(int value);
     ListQueryBuilder isGreaterThanOrEqualTo(int value);
     ListQueryBUilder isLessThanOrEqualTo(int value);
   }
   // ... matchers for other types of properties ...

   interface ListQueryBuilder {
      // Generic restrict methods
      StringWhereClause whereStringProperty(String propertyName);
      IntWhereClause whereIntProperty(String propertyName);
      // ...

      // Named restrict methods
      StringWhereClause whereName();
      StringWhereClause whereJobTitle();
      IntWhereClause whereEmployeeNumber();
      // ...

      ListQueryBuilder limit(long maximumSize);
      ListQueryBuilder offset(long index);

      ResultSet<Employee> fetch();
   }

   ListQueryBuilder list();
   ListenableFuture<Employee> getById(Key key);
   ListenableFuture<KeyOrError> add(Employee employee);
   ListenableFuture<Status> update(Key key, Employee employee);
   ListenableFuture<Status> delete(Key key);
}

附:

 interface ResultSet<T> {
    Iterable<T> asIterable();
    // ... other methods ...
 }

 interface KeyOrError {
    boolean isError();
    boolean isKey();
    Key getKey();
    Throwable getError();
 }

 interface Status {
   boolean isOk();
   boolean isError();
   Throwable getError();
   void verifyOk();
 }

基本上,这个想法是插入数据库会返回一个Key对象(如果不成功则返回错误)。 此密钥可用于检索,删除或更新数据库中的条目。 这些操作(添加,更新,删除和getById)都有一个结果,在这种情况下使用ListenableFuture<T>而不是类型T ; 此future对象允许您阻止(通过在将来的对象上调用.get() )或异步检索对象(通过注册在结果准备好时调用的回调)。

对于list-y操作,可以通过许多不同的方式对列表进行过滤,子选择,排序等。为了防止各种不同重载的组合爆炸,我们使用构建器模式允许应用这些不同的限制。多种组合。 简而言之,构建器接口提供了一种方法来处理零个或多个选项(排序,过滤器,限制等)以应用检索操作,然后调用fetch() ,这将导致执行列表查询并返回ResultSet 。 此操作返回ResultSet而不是ListenableFuture ,因为结果不是一次全部返回(例如,它们可能以流方式从数据库返回); ResultSet实际上是一个与ListenableFuture具有类似行为的接口,但是对于项目列表(项目可能在不同时间准备好)。 为方便起见,有一种方法可以轻松地迭代ResultSet的内容(例如,通过向ResultSet提供Iterable适配器); 但是,您可能还希望添加其他方法,以允许您在ResultSet上执行其他类型的异步处理; 例如,您可能需要ListenableFuture<T> reduce(T initialValue, ReduceFunction<T> reducer)来聚合结果集中的元素,并提供表示最终完成的对象。


There are a number of different options / approaches that are often taken:

  1. Blocking like the API you've shown. This is a very simple API to use, and parallelism can still be achieved by invoking the API from within a multithreaded application.

  2. Receiving/registering handlers in async operations. This is sometimes provided in combination with the blocking API (and, in fact, may be implemented in terms of the blocking API simply by spawning a background thread and then then invoking the handler at the end).

  3. Returning a Future or ListenableFuture object, which makes the interface more idiomatically Java-esque (by returning data in the return-type position), but representing the eventual result, not an immediately available result. The Future can then be used to block or non-block.

Personally, my recommendation here would be:

interface EmployeeDatabase {
   interface StringWhereClause {
     ListQueryBuilder is(String value);
     ListQueryBuilder contains(String value);
     ListQueryBUilder matchesRegex(String regex);
   }

   interface IntWhereClause {
     ListQueryBuilder is(int value);
     ListQueryBuilder isInRange(int min, int max);
     ListQueryBuilder isGreaterThan(int value);
     ListQueryBUilder isLessThan(int value);
     ListQueryBuilder isGreaterThanOrEqualTo(int value);
     ListQueryBUilder isLessThanOrEqualTo(int value);
   }
   // ... matchers for other types of properties ...

   interface ListQueryBuilder {
      // Generic restrict methods
      StringWhereClause whereStringProperty(String propertyName);
      IntWhereClause whereIntProperty(String propertyName);
      // ...

      // Named restrict methods
      StringWhereClause whereName();
      StringWhereClause whereJobTitle();
      IntWhereClause whereEmployeeNumber();
      // ...

      ListQueryBuilder limit(long maximumSize);
      ListQueryBuilder offset(long index);

      ResultSet<Employee> fetch();
   }

   ListQueryBuilder list();
   ListenableFuture<Employee> getById(Key key);
   ListenableFuture<KeyOrError> add(Employee employee);
   ListenableFuture<Status> update(Key key, Employee employee);
   ListenableFuture<Status> delete(Key key);
}

With:

 interface ResultSet<T> {
    Iterable<T> asIterable();
    // ... other methods ...
 }

 interface KeyOrError {
    boolean isError();
    boolean isKey();
    Key getKey();
    Throwable getError();
 }

 interface Status {
   boolean isOk();
   boolean isError();
   Throwable getError();
   void verifyOk();
 }

Basically, the idea is that insertion into the database returns a Key object (or an error if unsuccessful). This key can be used to retrieve, delete, or update the entry in the database. These operations (add, update, delete, and getById) all have a single result, in which case a ListenableFuture<T> is used instead of type T; this future object allows you to block (by calling .get() on the future object) or to retrieve the object asynchronously (by registering a callback to be invoked when the result is ready).

For list-y operations, there are many different ways that a list can be filtered, subselected, sorted, etc. In order to prevent a combinatoric explosion of various different overloads, we use the builder pattern to allow these different restrictions to be applied in multiple combinations. In short, the builder interface provides a way to tack on zero or more options (sorts, filters, limits, etc.) to apply the retrieval operation, before calling fetch() which causes the list query to be executed and returns a ResultSet. This operation returns a ResultSet rather than a ListenableFuture, because the results are not all returned at once (e.g. they may come back from the data base in streaming fashion); the ResultSet is effectively an interface with a similar behavior to a ListenableFuture but for lists of items (where items may be ready at different times). For convenience, it is important to have a way to easily iterate over the contents of the ResultSet (e.g. by providing an Iterable adapter to the ResultSet); however, you will probably also want to add other methods that allow you to perform other types of asynchronous processing on the ResultSet; for example, you might want a ListenableFuture<T> reduce(T initialValue, ReduceFunction<T> reducer) to aggregate the elements in the result set and provide a future object representing the eventual completion of that.

相关问答

更多
  • 使用异步方法,您可以在准备就绪时将数据发送到客户端,而不是在准备好的时候阻塞线程。 对于http-kit,您应该使用文档中描述的异步处理程序。 以正确的方式将请求委托给异步处理程序后,您可以实现它,不过您喜欢使用core.async或其他。 异步处理程序文档在这里: http : //http-kit.org/server.html#channel With the async approach you get to send the data to the client when its ready, i ...
  • 这是可能的,但不适用于JDBC。 除非你想使用原始SocketChannel接口并自己解析结果,否则JVM上唯一的异步数据库驱动程序是https://github.com/mauricio/postgresql-async (尽管名称也支持MySQL )。 它们是用Scala编写的,但应该可以从Java调用它们(因为它是JVM语言),但我不能说API对Java的友好程度如何。 It's possible, but not with JDBC. Unless you want to use the raw S ...
  • 最简单non-blocking代码形式是简单地避免锁定或同步。 这实际上让你走得很远。 如果使用其他线程也使用的某些资源(共享内存),则可以使用一些java.util.concurrent类。 如果您查看API文档,有些可以避免阻止或放宽某些要求。 通常只保证eventual consistency而不是立即/原子的变化。 这几乎让你一路走来。 遗憾的是,仍然存在一些用例,例如生产者 - 消费者场景,网络通信和I / O,在这些情况下,您无法真正避免“等待”某些事情。 但很酷的是,您仍然可以使用contin ...
  • 通常采用许多不同的选项/方法: 阻止就像您展示的API一样。 这是一个非常简单的API,并且仍然可以通过从多线程应用程序中调用API来实现并行性。 在异步操作中接收/注册处理程序 。 这有时与阻塞API一起提供(事实上,可以简单地通过生成后台线程然后在最后调用处理程序来实现阻塞API)。 返回Future或ListenableFuture对象,这使得界面更具惯用性(通过在返回类型位置返回数据),但表示最终结果,而不是立即可用的结果。 然后可以使用Future来阻止或阻止。 就个人而言,我的推荐是: inte ...
  • 那么,因为在发布这个问题之后我又看了一下mongoose文档,所以我找到了stream()函数,它完美地填充了非阻塞操作。 怪我,但我认为它可以在猫鼬文档中提到更多的冒犯: http : //mongoosejs.com/docs/api.html#query_Query-stream var query = templateData.find({}).stream(); query.on('data', function (doc) { // do something with the mongo ...
  • 在IO意义上阻塞 (如在阻塞IO中 )意味着启动IO的线程进入休眠状态,直到IO结果可用。 非阻塞IO (或异步IO )告诉相关驱动程序(内核,数据库驱动程序等)初始化IO操作,然后线程继续执行其他操作 。 根据您使用的技术,您可以在回调(例如Node.js),通道(Java),期货(C ++),promises(Node.js的较新版本)中处理异步IO结果(可能甚至是异常),任务(.Net),协同程序(C ++ 17)等 异步IO不使用线程使IO异步。 这是关键点。 向线程池抛出阻塞IO操作不会使其异步, ...
  • 竞争条件是一个线程可以评估old_head->next ,就在调用unique_ptr的析构函数时(或之后)删除节点old_head指向的那个。 The race condition is that one thread could evaluate old_head->next, just when (or after) your unique_ptr's destructor is called that deletes the node old_head points to.
  • 首先,MATLAB不对任何图形进行多线程处理,因此您必须具有创造性。 此外,如果您尝试在计算过程中进行一些绘图,则需要使用drawnow来刷新回调和渲染事件。 知道何时停止,你可以将按钮的图形句柄传递给你的计算,它可以检查每次迭代的值? 我有一个示例,它使用持久变量来跟踪当前迭代,并允许用户通过取消切换按钮来“暂停”计算。 function guiThing() figure(); hbutton = uicontrol('style', 'toggle', 'String', 'Star ...
  • @Danack发布的评论为我解决了这个问题。 我正在使用后台线程进行聆听,现在我不再被阻止和连接就好了。 The comment posted by @Danack solved the problem for me. I am using a background thread to do the listening and now I am no longer blocked and connecting just fine.
  • 问题是:这个解决方案在CPU使用方面有多好? 使用select / poll / epoll会更有效吗? 这非常低效。 这可能是处理多个连接的最糟糕方式。 考虑每个recv是一个系统调用:它需要一个上下文切换。 上下文切换并不昂贵,但在高频环路中计算上下文切换可能会占用CPU。 此外,如果你在一个电话和另一个电话之间睡觉,为了“软化循环”,你最终会在数据接收和处理之间付出延迟; 你拥有的联系越多,感觉就越高。 select基本上告诉内核:“我希望你监视这些fds集合,并在发生某些事情时立即发出信号。” 您的 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)