Jack N @ GitHub

Full stack AI Engineer, focus on: React, Next.js, node.js and .Net

浏览器(Cache)的缓存逻辑(HTTP条件请求)

1. 浏览器缓存

一般来说,一个GET请求在目标资源存在的情况下会返回一个状态码为“200 OK”的响应,目标资源的内容将直接存放在响应报文的主体部分。如果资源的内容不会轻易改变,那么我们希望客户端(如浏览器)在本地缓存获取的资源。对于针对同一资源的后续请求来说,如果资源内容不曾改变,那么资源内容就无须再次作为网络荷载予以响应。

确定资源是否发生变化可以采用两种策略。第一种就是让资源的提供者记录最后一次更新资源的时间,资源的荷载内容(Payload)和这个时间戳将一并作为响应提供给作为请求发送者的客户端。客户端在缓存资源内容时也会保存这个时间戳。等到下次需要针对同一资源发送请求时,它会将这个时间戳一并发送出去,此时服务端就可以根据这个时间戳判断目标资源在上次响应之后是否被修改过,然后做出针对性的响应。第二种是针对资源的内容生成一个“标签”,标签的一致性体现了资源内容的一致性,在HTTP规范中将这个标签称为ETag(Entity Tag)。

2. If-Modified-Since与If-None-Match

对于HTTP请求来说,缓存资源携带的最后修改时间戳和ETag分别保存在名为If-Modified-Since与If-None-Match的报头中。报头名称体现的含义如下:只有目标资源在指定的时间之后被修改(If-Modified-Since)或者目前资源的状态与提供的ETag不匹配(If-None-Match)的情况下才会返回资源的荷载内容。

以Chrome为例, 当服务端接收到针对某个资源的GET请求时,如果请求不具有上述这两个报头或者根据这两个报头携带的信息判断资源已经发生改变,那么它返回一个状态码为“200 OK”的响应。除了将资源内容作为响应主体,如果能够获取到该资源最后一次修改的时间(一般精确到秒),那么格式化的时间戳还会通过一个名为Last-Modified的响应报头提供给客户端。针对资源自身内容生成的标签,则会以ETag响应报头的形式提供给客户端。反之,如果做出相反的判断,服务端就会返回一个状态码为“304 Not Modified”的响应,这个响应不包含主体内容。一般来说,这样的响应也会携带Last-Modified报头和ETag报头。

3. Chrome

Network in Chroem
从Chrome的Network请求中可以看到,

  1. 发送的请求的Header中包含了If-Modified-Since与If-None-Match;
  2. 返回的内容,同样会包含Modified-Since与ETag;
  3. 对于没有内容更改的请求,Status Code为304 - Not Modified
  4. 对于304返回,Modified-Since与ETag 必然与请求的If-Modified-Since与If-None-Match分别一致;

4. 总结

  1. 客户端(浏览器)如果有缓存内容,发送请求时会在Header中包含If-Modified-Since与If-None-Match
  2. 当服务器内容没有修改时,服务器端会发送304给客户端,这是body内容可能为空;

1. 题目: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

e.g
输入:l1 = [1,2,5], l2 = [1,3,4]
输出:[1,1,2,3,4,5]

2. 思路 (迭代)

我们可以用迭代的方法来实现上述算法。当 l1 和 l2 都不是空链表时,判断 l1 和 l2 哪一个链表的头节点的值更小,将较小值的节点添加到结果里,当一个节点被添加到结果里之后,将对应链表中的节点向后移一位。

3. 代码

3.1. C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
ListNode preHead = new ListNode(-1);
ListNode pre = preHead;
while (l1 != null && l2 != null){
if(l1.val > l2.val){
pre.next = l2;
l2 = l2.next;
}else{
pre.next = l1;
l1 = l1.next;
}
pre = pre.next;
}
pre.next = l1==null? l2:l1;
return preHead.next;
}

3.2. Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
var mergeTwoLists = function(l1, l2) {
if(l1 === null) return l2;
if(l2 === null) return l1;

let preHead = new ListNode();
let last = preHead;
let cur ;
while(l1 !=null && l2!= null){
if(l1.val > l2.val){
cur = l2;
l2 = l2.next;
}else{
cur = l1;
l1 = l1.next;
}
last.next = cur;
last = cur;

}
last.next = l1 === null? l2:l1;

return preHead.next;
};

  • CLR:公共语言运行库(Common Language Runtime)
  • CIL:通用中间语言(Common Intermediate Language,简称CIL,亦称IL)
  • CTS:通用类型系统(Common Type System)
  • CLS:公共语言规范 (Common Language Specification)
  • FCL:框架类库(Framework Class Library)
  • BCL:基础类库(Base Class Library)
  • DLL:Dynamic Link Library,动态链接库,也称为元件,CLR与BCL都是由元件构成。
  • Assembly: 程序集,由编译器得到,供CLR进一步编译执行中间产物MSIL,一般表现为.DLL,或者.EXE格式,必须依靠CLR才能顺利执行。
  • CoreFX: 是经过完全重写的BCL,除了自身就具有跨平台执行的能力之外,其提供的API也不再是统一定义在少数几个单一的程序集中,而是经过有效分组之后被定义在各自独立的模块中。
  • PCL: 可移植类库 Portable Class Library (PCL)
  • .NET Standard: 我们可以将.NET Standard称为新一代的PCL,PCL提供的可移植能力仅仅限于创建时就确定下来的几种目标平台,但是.NET Standard做得更加彻底,因为它在设计的时候就已经考虑针对三大分支的复用。
  • POCO: Plain Old Class Object,也就是最基本的CLR Class

1. React 基本问题

1.1. React有什么特点

  1. 它使用虚拟DOM而不是真正的DOM。
  2. 它可以用服务器端渲染。
  3. 它遵循单向数据流或数据绑定。

1.2. React的主要优点。

  1. 它提高了应用的性能
  2. 可以方便地在客户端和服务器端使用
  3. 由于 JSX,代码的可读性很好
  4. React 很容易与 Meteor,Angular 等其他框架集成
  5. 使用React,编写UI测试用例变得非常容易

1.3. React有哪些限制

  1. React 只是一个库,而不是一个完整的框架
  2. 它的库非常庞大,需要时间来理解
  3. 新手程序员可能很难理解
  4. 编码变得复杂,因为它使用内联模板和 JSX

1.4. Virtual DOM 的工作原理。

Virtual DOM 是一个轻量级的 JavaScript 对象,它最初只是 real DOM 的副本。它是一个节点树,它将元素、它们的属性和内容作为对象及其属性。 React 的渲染函数从 React 组件中创建一个节点树。然后它响应数据模型中的变化来更新该树,该变化是由用户或系统完成的各种动作引起的。

Virtual DOM 工作过程有三个简单的步骤。

  1. 每当底层数据发生改变时,整个 UI 都将在 Virtual DOM 描述中重新渲染。
  2. 然后计算之前 DOM 表示与新表示的之间的差异。
  3. 完成计算后,将只用实际更改的内容更新 real DOM。

1.5. react diff 原理

  1. 把树形结构按照层级分解,只比较同级元素。
  2. 给列表结构的每个单元添加唯一的 key 属性,方便比较。
  3. React 只会匹配相同 class 的 component(这里面的 class 指的是组件的名字)
    合并操作,调用 component 的 setState 方法的时候, React 将其标记为 dirty.到每一个事件循环结束, React 检查所有标记 dirty 的 component 重新绘制.
  4. 选择性子树渲染。开发人员可以重写 shouldComponentUpdate 提高 diff 的性能。

1.6. React 项目用过什么脚手架

creat-react-app, Yeoman, umi 等

1.7. 如果进行三次setState会发生什么,循环执行setState组件会一直重新渲染吗

setState这个方法是用来告诉react组件数据有更新,有可能需要重新渲染。它是异步的,react通常会集齐一批需要更新的组件,然后一次性更新来保证渲染的性能,所以进行三次只有一次的效果,并不会导致多次渲染。

此外再使用setState改变状态之后,立刻使用this.state去拿最新的状态往往是拿不到的,如果需要最新的state做业务的话,可以在componentDidUpdate或者setState的回调函数里获取。

1.8. 调用 setState 之后发生了什么?

在代码中调用setState函数之后,React 会将传入的参数对象与组件当前的状态合并,然后触发所谓的调和过程(Reconciliation)。经过调和过程,React 会以相对高效的方式根据新的状态构建 React 元素树并且着手重新渲染整个UI界面。在 React 得到元素树之后,React 会自动计算出新的树与老树的节点差异,然后根据差异对界面进行最小化重渲染。在差异计算算法中,React 能够相对精确地知道哪些位置发生了改变以及应该如何改变,这就保证了按需更新,而不是全部重新渲染。

1.9. 什么是JSX

JSX 是JavaScript XML 的简写。是 React 使用的一种文件,它利用 JavaScript 的表现力和类似 HTML 的模板语法。这使得 HTML 文件非常容易理解。此文件能使应用非常可靠,并能够提高其性能。

1.10. 浏览器是否可以直接读取读取JSX?

浏览器只能处理 JavaScript 对象,而不能读取常规 JavaScript 对象中的 JSX。所以为了使浏览器能够读取 JSX,首先,需要用像 Babel 这样的 JSX 转换器将 JSX 文件转换为 JavaScript 对象,然后再将其传给浏览器。

1.11. vue和react适用的场景

  • vue适合webapp,适合做用户交互多,各种动态效果变化丰富的应用。特别是PC、手机的网页版,商城等页面。因为vue实现逻辑复杂的功能比较简单。
  • react适合oa系统,适合大批量的数据展示、适合做大型应用。特别适合公司的后台管理系统。因为react对那种比较复杂的交互,实现起来比较麻烦,没有vue方便。同时react的渲染原理是渲染整个组件树,所以,一方面是费性能,而且代码写起来逻辑复杂。但是react对批量数据操作很厉害。
  • 总而言之,项目要求比较高的适合使用react,因为react的社区更活跃一些,尤其是各种UI框架比较稳定、系统,可以信赖。Vue的社区也很活跃,但相对而言各种组件五花八门,大多数不够完善,缺乏系统性和迭代性,对于项目的后期维护和新手入手都不太友好。
  • 从应用上来看,react打出来的包会大一些,相对来说,vue的包小一些,如果项目场景对加载速度由要求,建议使用vue。

2. React 组件

2.1. 为什么说在React中,一切都是组件

组件是 React 应用 UI 的构建块。这些组件将整个 UI 分成小的独立并可重用的部分。每个组件彼此独立,而不会影响 UI 的其余部分。

2.2. React 中 render() 的目的。

每个React组件强制要求必须有一个 render()。它返回一个 React 元素,是原生 DOM 组件的表示。如果需要渲染多个 HTML 元素,则必须将它们组合在一个封闭标记内,例如 <form>、<group>、<div> 等。此函数必须保持纯净,即必须每次调用时都返回相同的结果。

2.3. React组件生命周期的阶段是什么?

React 组件的生命周期有三个不同的阶段:

  1. 初始渲染阶段:这是组件即将开始其生命之旅并进入 DOM 的阶段。
  2. 更新阶段:一旦组件被添加到 DOM,它只有在 prop 或状态发生变化时才可能更新和重新渲染。这些只发生在这个阶段。
  3. 卸载阶段:这是组件生命周期的最后阶段,组件被销毁并从 DOM 中删除。

2.4. react 生命周期函数

  1. 挂载
    当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
  • constructor()
  • getDerivedStateFromProps(): 当从父类接收到 props 并且在调用另一个渲染器之前调用。
  • render()
  • componentDidMount(): 仅在第一次渲染后在客户端执行。
  1. 更新
    当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
  • getDerivedStateFromProps(): 当从父类接收到 props 并且在调用另一个渲染器之前调用。
  • shouldComponentUpdate(): 根据特定条件返回 true 或 false。如果你希望更新组件,请返回true 否则返回 false。默认情况下,它返回 false。
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate(): 在渲染发生后立即调用
  1. 卸载
    当组件从 DOM 中移除时会调用如下方法:
  • componentWillUnmount(): 从 DOM 卸载组件后调用。用于清理内存空间。

2.5. 在生命周期中的哪一步你应该发起 AJAX 请求?

我们应当将AJAX 请求放到 componentDidMount 函数中执行,主要原因有下:

React 下一代调和算法 Fiber 会通过开始或停止渲染的方式优化应用性能,其会影响到 componentWillMount 的触发次数。对于 componentWillMount 这个生命周期函数的调用次数会变得不确定,React 可能会多次频繁调用 componentWillMount。如果我们将 AJAX 请求放到 componentWillMount 函数中,那么显而易见其会被触发多次,自然也就不是好的选择。 (新版本的React,已经拿掉了)

如果我们将 AJAX 请求放置在生命周期的其他函数中,我们并不能保证请求仅在组件挂载完毕后才会要求响应。如果我们的数据请求在组件挂载之前就完成,并且调用了setState函数将数据添加到组件状态中,对于未挂载的组件则会报错。而在 componentDidMount 函数中进行 AJAX 请求则能有效避免这个问题。

2.6. 展示组件(Presentational component)和容器组件(Container component)之间有何不同

  • 展示组件关心组件看起来是什么。展示专门通过 props 接受数据和回调,并且几乎不会有自身的状态,但当展示组件拥有自身的状态时,通常也只关心 UI 状态而不是数据的状态。
  • 容器组件则更关心组件是如何运作的。容器组件会为展示组件或者其它容器组件提供数据和行为(behavior),它们会调用 Flux actions,并将其作为回调提供给展示组件。容器组件经常是有状态的,因为它们是(其它组件的)数据源。

2.7. 调用 super(props) 的目的是什么

在 super() 被调用之前,子类是不能使用 this 的,在 ES2015 中,子类必须在 constructor 中调用 super()。

传递 props 给 super() 的原因则是便于(在子类中)能在 constructor 访问 this.props。

2.8. 除了在构造函数中绑定 this,还有其它方式吗

你可以使用属性初始值设定项(property initializers)来正确绑定回调,create-react-app 也是默认支持的。

在回调中你可以使用箭头函数,但问题是每次组件渲染时都会创建一个新的回调。

2.9. 什么是 Props?

Props 是 React 中属性的简写。它们是只读组件,必须保持纯,即不可变。它们总是在整个应用中从父组件传递到子组件。子组件永远不能将 prop 送回父组件。这有助于维护单向数据流,通常用于呈现动态生成的数据。

2.10. 什么是状态(State)?

状态是 React 组件的核心,是数据的来源,必须尽可能简单。基本上状态是确定组件呈现和行为的对象。与props 不同,它们是可变的,并创建动态和交互式组件。可以通过 this.state 访问它们。

2.11. 类组件(Class component)和函数式组件(Functional component)之间有何不同

  • 类组件不仅允许你使用更多额外的功能,如组件自身的状态和生命周期钩子,也能使组件直接访问 store 并维持状态 (React v16.8以后,可以使用hook使用state和部分生命周期钩子函数)
  • 当组件仅是接收 props,并将组件自身渲染到页面时,该组件就是一个 ‘无状态组件(stateless component)’,可以使用一个纯函数来创建这样的组件。这种组件也被称为哑组件(dumb components)或展示组件

2.12. 如何更新组件的状态?

  1. 可以用 this.setState()更新组件的状态
  2. 更新时,可以只更新部分属性,保留其他属性值

##React 中的箭头函数有什么作用
箭头函数(=>)是用于编写函数表达式的简短语法。这些函数允许正确绑定组件的上下文(不改变this),因为在 ES6 中默认下不能使用自动绑定。使用高阶函数时,箭头函数非常有用。

2.13. React中的事件是什么?

在 React 中,事件是对鼠标悬停、鼠标单击、按键等特定操作的触发反应。处理这些事件类似于处理 DOM 元素中的事件。但是有一些语法差异,如:

  1. 用驼峰命名法对事件命名而不是仅使用小写字母。
  2. 事件作为函数而不是字符串传递。

事件参数重包含一组特定于事件的属性。每个事件类型都包含自己的属性和行为,只能通过其事件处理程序访问。

2.14. React中的合成事件是什么?

合成事件是围绕浏览器原生事件充当跨浏览器包装器的对象。它们将不同浏览器的行为合并为一个 API。这样做是为了确保事件在不同浏览器中显示一致的属性。

2.15. 何为受控组件(controlled component)

在 HTML 中,类似 <input>, <textarea> 和 <select> 这样的表单元素会维护自身的状态,并基于用户的输入来更新。当用户提交表单时,前面提到的元素的值将随表单一起被发送。但在 React 中会有些不同,包含表单元素的组件将会在 state 中追踪输入的值,并且每次调用回调函数时,如 onChange 会更新 state,重新渲染组件。一个输入表单元素,它的值通过 React 的这种方式来控制,这样的元素就被称为”受控元素”。

2.16. React 的 refs 有什么作用?

Refs 是 React 中引用的简写。它是一个有助于存储对特定的 React 元素或组件的引用的属性,它将由组件渲染配置函数返回。用于对 render() 返回的特定元素或组件的引用。当需要进行 DOM 测量或向组件添加方法时,它们会派上用场。

2.17. 列出一些应该使用 Refs 的情况

  • 需要管理焦点、选择文本或媒体播放时
  • 触发式动画
  • 与第三方 DOM 库集成

2.18. shouldComponentUpdate 是做什么的,(react 性能优化是哪个周期函数?)

shouldComponentUpdate 这个方法用来判断是否需要调用 render 方法重新描绘 dom。因为 dom 的描绘非常消耗性能,如果我们能在 shouldComponentUpdate 方法中能够写出更优化的 dom diff 算法,可以极大的提高性能。

2.19. 什么是高阶组件(HOC - higher order component)?

高阶组件是重用组件逻辑的高级方法,是一种源于 React 的组件模式。 HOC 是自定义组件,在它之内包含另一个组件。它们可以接受子组件提供的任何动态,但不会修改或复制其输入组件中的任何行为。你可以认为 HOC 是“纯(Pure)”组件。

2.20. 你能用HOC做什么?

  • 代码重用,逻辑和引导抽象
  • 渲染劫持
  • 状态抽象和控制
  • Props 控制

2.21. 什么是纯组件(Pure Component)?

纯(Pure) 组件是可以编写的最简单、最快的组件。它们可以替换任何只有 render() 的组件。这些组件增强了代码的简单性和应用的性能。

2.22. React 中 key 的重要性是什么?

key 用于识别唯一的 Virtual DOM 元素及其驱动 UI 的相应数据。它们通过回收 DOM 中当前所有的元素来帮助 React 优化渲染。这些 key 必须是唯一的数字或字符串,React 只是重新排序元素而不是重新渲染它们。这可以提高应用程序的性能。

3. Redux

3.1. 什么是Flux

Flux 是一种强制单向数据流的架构模式。它控制派生数据,并使用具有所有数据权限的中心 store 实现多个组件之间的通信。整个应用中的数据更新必须只能在此处进行。 Flux 为应用提供稳定性并减少运行时的错误。

3.2. 什么是Redux?

Redux 是当今最热门的前端开发库之一。它是 JavaScript 程序的可预测状态容器,用于整个应用的状态管理。使用 Redux 开发的应用易于测试,可以在不同环境中运行,并显示一致的行为。

3.3. Redux遵循的三个原则是什么?

  1. 单一事实来源:整个应用的状态存储在单个 store 中的对象/状态树里。单一状态树可以更容易地跟踪随时间的变化,并调试或检查应用程序。
  2. 状态是只读的:改变状态的唯一方法是去触发一个动作。动作是描述变化的普通 JS 对象。就像 state 是数据的最小表示一样,该操作是对数据更改的最小表示。
  3. 使用纯函数进行更改:为了指定状态树如何通过操作进行转换,你需要纯函数。纯函数是那些返回值仅取决于其参数值的函数。

3.4. “单一事实来源”有什么理解?

Redux 使用 “Store” 将程序的整个状态存储在同一个地方。因此所有组件的状态都存储在 Store 中,并且它们从 Store 本身接收更新。单一状态树可以更容易地跟踪随时间的变化,并调试或检查程序。

3.5. 列出 Redux 的组件

  • Action – 这是一个用来描述发生了什么事情的对象。React 中的 Action 必须具有 type 属性,该属性指示正在执行的 ACTION 的类型。必须将它们定义为字符串常量,并且还可以向其添加更多的属性。在 Redux 中,action 被名为 Action Creators 的函数所创建。
  • Reducer – 这是一个确定状态将如何变化的地方。Reducers 是纯函数,它规定应用程序的状态怎样因响应 ACTION 而改变。Reducers 通过接受先前的状态和 action 来工作,然后它返回一个新的状态。它根据操作的类型确定需要执行哪种更新,然后返回新的值。如果不需要完成任务,它会返回原来的状态。
  • Store – 整个程序的状态/对象树保存在Store中。 Store 是一个 JavaScript 对象,它可以保存程序的状态,并提供一些方法来访问状态、调度操作和注册侦听器。
  • View – 只显示 Store 提供的数据。

3.6. Redux与Flux的区别

Flex Redux
Store 包含状态和更改逻辑 Store 和更改逻辑是分开的
有多个 Store 只有一个 Store
所有 Store 都互不影响且是平级的 带有分层 reducer 的单一 Store
有单一调度器 没有调度器的概念
React 组件订阅 store 容器组件是有联系的
状态是可变的 状态是不可改变的

3.7. Redux 有哪些优点?

  • 结果的可预测性 - 由于总是存在一个真实来源,即 store ,因此不存在如何将当前状态与动作和应用的其他部分同步的问题。
  • 可维护性 - 代码变得更容易维护,具有可预测的结果和严格的结构。
  • 服务器端渲染 - 你只需将服务器上创建的 store 传到客户端即可。这对初始渲染非常有用,并且可以优化应用性能,从而提供更好的用户体验。
  • 开发人员工具 - 从操作到状态更改,开发人员可以实时跟踪应用中发生的所有事情。
  • 社区和生态系统 - Redux 背后有一个巨大的社区,这使得它更加迷人。一个由才华横溢的人组成的大型社区为库的改进做出了贡献,并开发了各种应用。
  • 易于测试 - Redux 的代码主要是小巧、纯粹和独立的功能。这使代码可测试且独立。
  • 组织 - Redux 准确地说明了代码的组织方式,这使得代码在团队使用时更加一致和简单。

4. React Router

4.1. 为什么需要 React 中的路由?

Router 用于定义多个路由,当用户定义特定的 URL 时,如果此 URL 与 Router 内定义的任何 “路由” 的路径匹配,则用户将重定向到该特定路由。所以基本上我们需要在自己的应用中添加一个 Router 库,允许创建多个路由,每个路由都会向我们提供一个独特的视图。

4.2. 什么是React 路由?

React 路由是一个构建在 React 之上的强大的路由库,它有助于向应用程序添加新的屏幕和流。这使 URL 与网页上显示的数据保持同步。它负责维护标准化的结构和行为,并用于开发单页 Web 应用。 React 路由有一个简单的API。

4.3. React Router 的优点。

  • 就像 React 基于组件一样,在 React Router v4 中,API 是 ‘All About Components’。可以将 Router 可视化为单个根组件(),其中我们将特定的子路由()包起来。
  • 无需手动设置历史值:在 React Router v4 中,我们要做的就是将路由包装在 组件中。
  • 包是分开的:共有三个包,分别用于 Web、Native 和 Core。这使我们应用更加紧凑。基于类似的编码风格很容易进行切换

前端进阶(2)使用fetch/axios时, 如何取消http请求

1. 需求

现在前端都是SPA,我们什么时候需要取消HTTP请求呢?

  1. 当我们从一个页面跳转到另外一个页面时,如果前一个页面的请求还没有返回,那么我们希望取消前一个页面的请求
  2. 某些操作耗时比较长(不能是保存等操作哦),如果用户不想等待呢,取消了操作,对应我们也需要取消HTTP请求

对于原生的XMLHttpRequest,是支持取消http请求(abort)操作的: XMLHttpRequest.abort()
那么,当我们使用ES6的fetch,或者使用axios库,如何实现呢?

2. Fetch 取消http请求

fetch与XMLHttpRequest(XHR)类似,是ES6之后浏览器(除IE之外)默认支持的http操作函数。可惜不是默认支持abort操作。但我们可以通过AbortController来实现, 直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 声明AbortController
const controller = new AbortController();

// 正常的http调用
fetch('https://jackniu81.github.io', { signal: controller.signal })
.then(r => r.json())
.then(response => {
console.log(response);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch was aborted')
} else {
console.log('Error', err)
}
});

// 需要取消请求时,调用:
controller.abort()

3. axios取消http请求

axios 已经实现了abort操作,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var source = axios.CancelToken.source();

axios.get('https://jackniu81.github.io', {
cancelToken: source.token
}).catch(function(err) {
if (axios.isCancel(err)) {
// handle our cancel operation
console.log('Request canceled', err.message);
} else {
// handle real error here
}
});

// 需要取消请求时,调用:
source.cancel('Abort Request');

4. jquery 取消http请求

$.ajax内部已经实现了abort功能。直接调用.abort()即可。

5. 总结

  1. fetch与AbortController集成:我们将signal属性作为可选参数(option)进行传递,之后 fetch 会监听它,因此它能够中止 fetch.
  2. AbortController 是可伸缩的,可以用于一次性终止多个请求;
  3. 参考fetch的实现,我们自己的代码也完善一下,实现基于AbortController操作取消操作;
  4. axios 默认支持Abort操作;

前端进阶(1)Web前端性能优化

Web前端性能优化, 不仅能够改善站点的用户体验,并且能够节省相当的资源利用。下面将从1)服务器、2)html内容、3)css、 4)javascript、 5)图片等几方面介绍具体的优化操作。

目录:

1. 服务器优化

1.1. 使用内容分发网络(CDN)

把网站内容分散到多个、处于不同地域位置的服务器上可以加快下载速度。

1.2. 服务器使用http2.0协议

Http2.0的优点

  1. 二进制分帧
  2. 首部压缩
  3. 流量控制
  4. 多路复用
  5. 请求优先级
  6. 服务器推送

e.g 使用nginx, 要求 1)v1.9.5以上, 2)使用https;

1.3. GZIP压缩

1.4. 使用浏览器缓存

CSS、javascript、logo、图标这些静态资源文件更新的频率都比较低,而这些文件又几乎是每次http请求都需要的,如果将这些文件缓存在浏览器中,可以极好的改善性能。

通过设置http头中的cache-control和expires的属性,可设定浏览器缓存,减少网络请求次数。

1.5. 设置ETag

ETags(Entity tags,实体标签)是web服务器和浏览器用于判断浏览器缓存中的内容和服务器中的原始内容是否匹配的一种机制。

2. HTML内容优化

2.1. 减少HTTP请求数

这条策略是最重要最有效的,因为一个完整的请求要经过DNS寻址,与服务器建立连接,发送数据,等待服务器响应,接收数据这样一个消耗时间成本和资源成本的复杂的过程。 常见方法:

  1. 合并多个CSS文件和js文件, 并进行最小化处理。
  2. 利用CSS Sprites整合图像,
  3. 行内图片Base64编码,使用 data:URL scheme在实际的页面嵌入图像数据
  4. 合理设置HTTP缓存

2.2. 减少DNS查找

为了减少DNS的询次数,最好的解决方法就是在页面中减少不同的域名请求的机会。

2.3. 避免重定向 301/30x

如果重定向的话,就需要在访问过程中重复发起一连串的动作,会消耗很多时间,因此避免出现多次重定向地址或资源的访问。

2.4. 避免在html标签中写style属性

js,css 写到单独的文件中,便于浏览器缓存。

2.5. 异步加载组件,预加载组件 (ansyc, defer)

ansyc, defer不会阻塞浏览器的文档解析。

  1. ansyc用于异步加载
  2. defer用于预加载

2.6. 延迟、分页加载图片

对于图片而言,在页面刚加载的时候可以只加载第一屏,当用户继续往后滚屏的时候才加载后续的图片。这样一来,假如用户只对第一屏的内容感兴趣时,那剩余的图片请求就都节省了。

2.7. 减少DOM元素数量

页面中存在大量DOM元素,会导致javascript遍历DOM的效率变慢。

2.8. 最小化iframe的数量

iframes 提供了一个简单的方式把一个网站的内容嵌入到另一个网站中。但其创建速度比其他包括JavaScript和CSS的DOM元素的创建慢了1-2个数量级。

2.9. 避免404

HTTP请求时间消耗是很大的,因此使用HTTP请求来获得一个没有用处的响应(例如404没有找到页面)是完全没有必要的,它只会降低用户体验而不会有一点好处。

2.10. 对Ajax请求使用GET方法

2.11. 避免空的图像src

3. CSS优化

3.1. 将CSS代码放在HTML页面的顶部

3.2. 合并、压缩CSS

3.3. CSS选择符优化

  1. 浏览器对选择符的解析是从右往左进行的
  2. 按照ID查询效率最高

3.4. 避免使用CSS表达式

3.5. 使用来代替@import

3.6. 避免使用Filters

4. javascript优化

4.1. 将JavaScript脚本放在页面的底部

4.2. 将JavaScript和CSS作为外部文件来引用

在实际应用中使用外部文件可以提高页面速度,因为JavaScript和CSS文件都能在浏览器中产生缓存。

4.3. 合并、压缩JavaScript

4.4. 删除无用、重复的脚本

4.5. 最小化DOM的访问

使用JavaScript访问DOM元素比较慢

4.6. 开发智能的事件处理程序

4.7. javascript代码注意

  1. 减少作用域链查找(多用局部变量,少访问全局变量)
  2. 减少闭包的使用,避免内存泄漏
  3. 谨慎使用with
  4. 避免使用eval Function函数
  5. 字符串拼接, Javascript中使用”+” 号来拼接字符串效率是比较低,建议使用数组的 join方法

5. 图像优化

5.1. 优化图片大小

5.2. 通过CSS Sprites优化图片

5.3. 不要在HTML中使用缩放图片

5.4. favicon.ico要小而且可缓存

6. 其他

6.1. 减小Cookie大小,尽量不使用cookie

cookie包含在每次请求和响应中,太大的cookie会严重影响数据传输

6.2. 负载均衡

负载均衡load balancer,降低每个站点的请求书,提高单个请求的响应时间。

https://jackniu81.github.io/2021/04/22/2021-Top-100-C-NET-Interview-Questions-And-Answers/

1. What is the difference between “dispose” and “finalize” variables in C#?

  1. Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
  2. Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

2. What does “Jagged Arrays” mean?

Answer: Jagged arrays refer to the array that has an element of type array. The dimensions and the sizes of the elements are different. An array of arrays is the other name of the jagged array.

3. What is a Class and an Object?

A ‘Class’ is an encapsulation of methods and properties that are used to represent an entity in real-time. Class brings all of the instances together in a single unit. An ‘Object’ is an instance of a Class, or a block of allocated memory that can be stored in the form of Variables, Array or a Collection.

4. Explain Code compilation in C#

Code compilation has four steps which include:

  1. Compiling source code to Managed code by C# compiler
  2. Executing the assembly by CLR
  3. Combining the new code into assemblies
  4. Loading the Common Language Runtime (CLR)

5. What is the difference between Virtual method and Abstract method?

A Virtual method must always have a default implementation. An Abstract method does not have an implementation. An override keyword is not necessary here, though it can be used.

6. What is a Hashtable in C#?

A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in a Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. Access to the table’s values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.

7. What is LINQ in C#?

LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query.

LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface.

Advantages of LINQ

  • LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we can query a database and XML as well as collections.
  • Compile-time syntax checking.

8. What are Indexers in C#?

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not an essential part of object-oriented programming.

Defining an indexer allows you to create classes that act as virtual arrays. Instances of that class can be accessed using the [] array access operator.

9. Difference between the Equality Operator (==) and Equals() Method in C#

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents.

10. What’s the Difference between the Is and As operator in C#

  • “is” operator: In C# language, we use the “is” operator to check the object type. If two objects are of the same type, it returns true, else it returns false.

  • “as” operator: The “as” operator behaves in a similar way as the “is” operator. The only difference is it returns the object if both are compatible with that type. Else it returns a null.

11. What are Different Ways a Method can be Overloaded?

Method overloading is a way to achieve compile-time polymorphism where we can use a method with the same name but different signatures. For example, the following code example has a method volume with three different signatures based on the number and type of parameters and return values.

12. What is Serialization?

Serialization converts a code to its binary format using a process. After it is converted to bytes, it can be easily stored and written to a disk. Serializations are useful so that the original form of the code isn’t lost and it can be retrieved later on.

13. What are the different types of Delegates?

The different types of Delegates are: Single Delegate, Multicast Delegate and Generic Delegate.

14. How to use extension methods?

An extension method is a static method of a static class, where the “this” modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

15. What is the difference between String and StringBuilder in C#?

StringBuilder and string are both used to string values, but both have many differences on the bases of instance creation and also in performance.

16. What are sealed classes in C#?

Sealed classes are used to restrict the inheritance feature of object-oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of the sealed class. If a class is derived from a sealed class then the compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

17. What is a Delegate? Explain.

A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System.Delegate namespace. Both Delegate and the method that it refers to can have the same signature.

Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created by the delegate using the new keyword.

1
AddNumbers an1 = new AddNumbers(number);

The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
public delegate int myDel(int number);
public class Program
{
public int AddNumbers(int a)
{
int Sum = a + 10;
return Sum;
}
public void Start()
{
myDel DelgateExample = AddNumbers;
}
}

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers().

If there is another method called Start() which creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.

18. What are Events?

Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress and so on.

Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber. Event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

1
2
Public delegate void PrintNumbers();
Event PrintNumbers myEvent;

19. How to use Delegates with Events?

Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

20. What do Multicast Delegates mean?

A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.

21. Explain Publishers and Subscribers in Events.

Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event as discussed in the above questions.

From the Example in Q #32, Class Patient is the Publisher class. It is generating an Event deathEvent, which is received by the other classes.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Q#32, Class Insurance and Bank are Subscribers. They are interested in event deathEvent of type void.

22. What are Synchronous and Asynchronous operations?

Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time. The asynchronous call waits for the method to complete before continuing with the program flow.

Synchronous programming badly affects the UI operations when the user tries to perform time-consuming operations since only one thread will be used. In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

In C#, Async and Await keywords are used to achieve asynchronous programming. Look at Q #43 for more details on synchronous programming.

23. What is Reflection in C#?

Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.

The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, For Example, to view the properties of a button in a windows form.

The MemberInfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get type of a class, we can simply use,

1
Type mytype = myClass.GetType();

Once we have a type of class, the other information about the class can be easily accessed.

1
System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);

Above statement tries to find a method with name AddNumbers in the class myClass.

24. What is a Generic Class?

Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be assigned during runtime, i.e when it is used in the program.

In case of other data type parameter comparisons, instead of creating many overloaded methods, we can create a generic class and pass a substitute data type, i.e T. So, T acts as a datatype until it is used specifically in the Main() method.

25. What is a Jagged Array?

A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.

int[] jaggedArray = new int[4][];

#) Name some properties of Array.

Properties of an Array include:

  • Length: Gets the total number of elements in an array.
  • IsFixedSize: Tells whether the array is fixed in size or not.
  • IsReadOnly: Tells whether the array is read-only or not.

26. What is an Array Class?

An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace system.

27. What is a String? What are the properties of a String Class?

A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;
A string class in C# represents a string. The properties of the string class are:

  • Chars get the Char object in the current String.
  • Length gets the number of objects in the current String.

28. Name some properties of Thread Class.

Few Properties of thread class are:

  • IsAlive – contains value True when a thread is Active.
  • Name – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
  • ThreadState– describes the thread state.

29. What are the different states of a Thread?

Different states of a thread are:

  • Unstarted – Thread is created.
  • Running – Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – Thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

30. What are Async and Await?

Async and Await keywords are used to create asynchronous methods in C#.

Asynchronous programming means that the process runs independently of main or other processes.

31. Async Keyword

Async keyword is used for the method declaration.

32. What is a Deadlock?

A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

33. Explain Lock, Monitors, and Mutex Object in Threading.

  • Lock keyword ensures that only one thread can enter a particular section of the code at any given time. lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

  • Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

  • Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.

1
2
3
4
5
6
7
Monitor.Enter(ObjA);
try
{
}
Finally {
Monitor.Exit(ObjA));
}

34. What is a Race Condition?

Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.

If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value to X, the last value written to X will be saved.

35. What is Thread Pooling?

Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.

System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.

36. What is Serialization?

Serialization is a process of converting code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the C# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

37. What are the types of Serialization?

The different types of Serialization are:

  • XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
  • SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.
  • Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

38. What is an XSD file?

An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to the XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

39. What is an Object and a Class?

  • Class is an encapsulation of properties and methods that are used to represent a real-time entity. It is a data structure that brings all the instances together in a single unit.

  • Object is defined as an instance of a Class. Technically, it is just a block of memory allocated that can be stored in the form of variables, array or a collection.

40. What are the fundamental OOP concepts?

The four fundamental concepts of Object-Oriented Programming are:

  • Encapsulation: Here, the internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
  • Abstraction: It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
  • Inheritance: It is the ability to create new classes from another class. It is done by accessing, modifying and extending the behavior of objects in the parent class.
  • Polymorphism: The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

41. What is Managed and Unmanaged code?

Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code is based on .Net platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. The application runtime will take care of memory, security and other performance operations.

42. What is an Interface?

Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.

43. Explain Get and Set Accessor properties?

Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.

  1. Get Property is used to return the value of a property
  2. Set Property accessor is used to set the value.

44. What is a Thread? What is Multithreading?

A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.

Threads are created by extending the Thread Class. Start() method is used to begin thread execution.

1
2
3
4
//CallThread is the target method//
ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.Start();

C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.

There are several thread methods that are used to handle multi-threaded operations: Start, Sleep, Abort, Suspend, Resume and Join.

45. What is “using” statement in C#?

“Using” keyword denotes that the particular namespace is being used by the program.

For Example, using System

Here, System is a namespace. The class Console is defined under System. So, we can use the console.writeline (“….”) or readline in our program.

46. Explain Abstraction.

Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hide unnecessary information.

Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using the private keyword.

47. What are C# I/O classes? What are the commonly used I/O classes?

C# has System.IO namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.

Some commonly used I/O classes are:

  • File – Helps in manipulating a file.
  • StreamWriter – Used for writing characters to a stream.
  • StreamReader – Used for reading characters to a stream.
  • StringWriter – Used for reading a string buffer.
  • StringReader – Used for writing a string buffer.
  • Path – Used for performing operations related to the path information.

48. What is StreamReader/StreamWriter class?

StreamReader and StreamWriter are classes of namespace System.IO. They are used when we want to read or write charact90, Reader-based data, respectively.

Some of the members of StreamReader are: Close(), Read(), Readline().

Members of StreamWriter are: Close(), Write(), Writeline().

1
2
3
4
5
6
7
8
9
10
11
Class Program1
{
using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
{
//----------------code to read-------------------//
}
using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
{
//-------------code to write-------------------//
}
}

49. What is a Destructor in C#?

Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.

For Example:

1
2
3
4
~Car()
{
Console.writeline(“….”);
}

50. What is an Abstract Class?

An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. This class should always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then such classes can be made abstract.

Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.

For Example:

1
2
3
4
5
6
7
8
9
abstract class AB1
{
Public void Add();
}
Class childClass : AB1
{
childClass cs = new childClass ();
int Sum = cs.Add();
}

All the methods in an abstract class are implicitly virtual methods. Hence, the virtual keyword should not be used with any methods in the abstract class.

51. How can one use nullable types in .Net?

Nullable types are defined as the types which can either take the normal value or the null value.

52. How to use nullable types in .Net?

Value types can take either their normal values or a null value. Such types are called nullable types.

1
2
3
4
Int? someID = null;
If(someID.HasVAlue)
{
}

53. What is the difference between Continue and Break Statement?

Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.

54. What is the difference between finally and finalize block?

finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.

finalize method is called just before garbage collection. It is used to perform clean up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.

55. What is an Array? Give the syntax for a single and multi-dimensional array?

An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

For Example:

1
2
double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single dimensional array is a linear array where the variables are stored in a single row. Above example is a single dimensional array.

Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example, int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };

56. What are Boxing and Unboxing?

Converting a value type to reference type is called ‘Boxing’. Explicit conversion of the same reference type that is created by boxing back to value type is called ‘Unboxing’.

57. What is an Array used for?

An Array is used to store multiple variables of the same type and is a collection of variables stored in a contiguous memory location.

58. What is an Escape Sequence? Name the sequences in C

An Escape sequence is denoted by a backslash (). The backslash indicates that the character that follows it should be interpreted literally or that it is a special character. An escape sequence is considered as a single character.

59. What are the basic String Operations?

The basic String Operations are: Concatenate, Modify, Search, Compare.

60. What is an Escape Sequence? Name some String escape sequences in C#.

An Escape sequence is denoted by a backslash (). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.

String escape sequences are as follows:

  • \n – Newline character
  • \b – Backspace
  • \ – Backslash
  • \’ – Single quote
  • \’’ – Double Quote

61. In C#.Net, what do indexers mean?

In C#, indexers are also known as smart arrays. They allow the instances of the class that are to be indexed in a similar as that of the array.

62. What are Regular expressions? Search a string using regular expressions?

Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals. Regex is used for string parsing and replacing the character string.

For Example:

  • matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab and so on.

Searching a string using Regex:

1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
string[] languages = { "C#", "Python", "Java" };
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))
{
Console.WriteLine("Match found");
}
}
}

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch which returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

63. State the difference between direct cast and ctype.

The difference between direct cast and ctype is that direct cast is used for the conversion of type of an object that requires the run time which is similar to the specified type in the direct cast. Whereas ctype is used for converting the conversion which is defined for the expression and the type.

64. How can one use the singleton design pattern in C#?

The singleton design pattern is used in C# when the class has one instance and the access is provided globally.

65. What are the basic String Operations? Explain.

Some of the basic string operations are:

  • Concatenate: Two strings can be concatenated either by using a System.String.Concat or by using + operator.
  • Modify: Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
  • Compare: System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
  • Search: StartWith, EndsWith methods are used to search a particular string.

66. What is Parsing? How to Parse a Date Time String?

Parsing converts a string into another data type.

For Example:

1
2
string text = “500”;
int num = int.Parse(text);

500 is an integer. So, the Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.

1
2
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

67. What are extension methods in C#?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

68. What is the difference between the Virtual method and the Abstract method?

The Virtual method must always have a default implementation. However, it can be overridden in the derived class, although it is not mandatory. It can be overridden using the override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

69. What are the types of errors in C#?

Answer: Following are the two types of error in C#:

  1. Compile-time error
  2. Run time error

70. What is the difference between method overriding and method overloading?

In method overriding, we change the method definition in the derived class that changes the method behavior.

Method overloading is creating a method with the same name within the same class having different signatures.

71. Why can’t you specify the accessibility modifier for methods inside the interface?

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.

72. What is an object pool in .NET?

An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

73. What is the difference between read-only and constant?

The difference between read-only and constant is that read-only is used during run time when the value has to be assigned. Constant variables are used during compilation time for declaration and initialization.

74. What are partial classes?

A partial class is only used to split the definition of a class in two or more classes in the same source code file or more than one source file. You can create a class definition in multiple files, but it will be compiled as one class at run time. Also, when you create an instance of this class, you can access all the methods from all source files with the same object.

Partial Classes can be created in the same namespace. It isn’t possible to create a partial class in a different namespace. So use the “partial” keyword with all the class names that you want to bind together with the same name of a class in the same namespace.

75. Can “this” be used in a static method?

No, “this” cannot be used in a static method as static methods are used for either static variables or static methods.

76. What is IEnumerable<> in C#?

IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.

77. What is the difference between late binding and early binding in C#?

Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object-oriented programming that allows a language to use the same name in different forms. For example, a method named Add can add integers, doubles, and decimals.

78. What is the Constructor Chaining in C#?

Constructor chaining is a way to connect two or more classes in a relationship as Inheritance. In Constructor Chaining, every child class constructor is mapped to a parent class Constructor implicitly by base keyword, so when you create an instance of the child class, it will call the parent’s class Constructor. Without it, inheritance is not possible.

79. What’s the difference between the Array.CopyTo() and Array.Clone()?

The Array.Clone() method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

The CopyTo() static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.

80. Can Multiple Catch Blocks be executed in C#?

We can use multiple catch blocks with a try statement. Each catch block can catch a different exception. The following code example shows how to implement multiple catch statements with a single try statement.

81. What are Value types and Reference types in C#?

In C#, data types can be of two types, value types, and reference types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently operate on their values, Value type data types are stored on a stack and reference data types are stored on a heap.

In C#, basic data types include int, char, bool, and long, which are value types. Classes and collections are reference types.

82. How do you use the “using” statement in C#?

There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let’s explain!

  1. using Directive
    Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties on the current page. Adding a namespace can be done in the following two ways:
  2. Using Statement
    This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.

83. What are Anonymous Types in C#?

Anonymous types allow us to create new types without defining them. This is a way of defining read-only properties in a single object without having to define each type explicitly. Here, Type is generated by the compiler and is accessible only for the current block of code. The type of properties is also inferred by the compiler.

We can create anonymous types by using “new” keyword together with the object initializer.

84. Explain “static” keyword in C#?

“Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.

85. What are the different types of classes in C#?

The different types of class in C# are

  1. Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword ‘Partial’.
    Sealed class – It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword ‘Sealed’.
  2. Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword ‘abstract’.
  3. Static class – It is a class which does not allow inheritance. The members of the class are also static. It is denoted by the keyword ‘static’. This keyword tells the compiler to check for any accidental instances of the static class.

86. What is Managed and Unmanaged code?

Managed code is a code that is executed by CLR (Common Language Runtime). It is called ‘managed code’ because of the .Net framework which uses the garbage collector internally to clear up unused memory. ‘__Unmanaged code’ is any code that is executed by the application runtime of any other framework apart from .Net. The application runtime will take care of security, memory and other performance operations.

87. Explain Namespaces in C#

Namespaces are used to organize large code projects. “System” is the most widely-used namespace in C#.

88. Explain Polymorphism

In programming, polymorphism means the same method but different implementations. It contains two types, Compile-time and Runtime. Compile time polymorphism is accomplished by operator overloading. Runtime polymorphism is accomplished by overriding. An example would be: a class has a method Void Add(), polymorphism is accomplished by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

89. How is Exception Handling implemented in C#?

Exception handling is done using four keywords in C#:

  1. Try – contains a block of code that checks an exception.
  2. Catch – is a program that catches an exception with the help of exception handler.
  3. Finally – is a block of code written to execute even if an exception is not caught.
  4. Throw – Throws an exception when a problem occurs.

问题

umi推荐使用yarn安装,安装umi后,使用umi提示不是内部或者外部命令。(’umi’ is not recognized as an internal or external command,operable program or batch file.)

解决

根源在于yarn的global bin目录不在path环境变量的中,解决办法:

  1. 执行yarn global bin, 得到global bin目录
  2. 把global bin目录添加到环境变量path中
  3. 测试 umi -v

问题

最近访问GitHub总是不稳定,经常连不上, 出各种错误(OpenSSL SSL_read: Connection was reset, errno 10054, Connection refused …)。

原因大概是GitHub的IP经常变化(一天可能变几次),我们本地的DNS解析有问题,解决办法就是查询github的IP,手工写到我们的hosts文件中。

查询GitHub最新IP

  1. 访问 https://github.com.ipaddress.com/
  2. IP Address 即为IP地址
    github ip

修改hosts文件

  1. 目录:C:\Windows\System32\drivers\etc
  2. 打开 hosts文件
  3. 结尾增加一行 140.82.112.4 github.com (IP 用你查询到的最新的IP)
  4. 搞定,测试一下

说明,hosts文件, 可以给github.com添加多条IP记录,这样当我们访问github时,会一次尝试每个IP是否可以访问,如果都不行,会去Internet上做DNS解析。
可以这样配置

1
2
3
4
140.82.112.4	github.com
140.82.113.4 github.com
140.82.112.3 github.com
140.82.114.4 github.com

https://jackniu81.github.io/2021/04/18/Algorithm-Fibonacci-numbers/

1. 斐波那契数列

斐波那契数列:0, 1, 1, 2, 3, 5, 8, 13 … …

通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。

1
2
F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1

敏捷开发时,我们估算Story Point,通常就是使用斐波那契数列。

2. 解题思路

2.1. 递归

F(n) = F(n - 1) + F(n - 2), 很简单,就不谈了。

2.2. 动态规划

动态规划的思想是,记录中间计算结果,计算后面相时,根据前面保存的结果直接计算,避免重复计算。

3. Javascript 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if(n===0)
return 0;
if(n===1)
return 1;

let arr = [0,1]
for(let i=2;i<=n;i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
};

还可以进一步优化,当前使用数组记录以及计算过的F(n),由于F(n) = F(n - 1) + F(n - 2),实际只需要记录最近的2个值即可,不需要使用数组记录全部数据。

0%