GVKun编程网logo

typeof!==“未定义” vs. = null(c语言typeof未定义)

18

在本文中,我们将带你了解typeof!==“未定义”vs.=null在这篇文章中,我们将为您详细介绍typeof!==“未定义”vs.=null的方方面面,并解答c语言typeof未定义常见的疑惑,同

在本文中,我们将带你了解typeof!==“未定义” vs. = null在这篇文章中,我们将为您详细介绍typeof!==“未定义” vs. = null的方方面面,并解答c语言typeof未定义常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的angular – 在typescript中定义typeof抽象类、angularjs – TypeError:无法读取[null]中未定义的属性’post’、c# – typeof(DateTime?).Name == Nullable`1、c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?

本文目录一览:

typeof!==“未定义” vs. = null(c语言typeof未定义)

typeof!==“未定义” vs. = null(c语言typeof未定义)

我经常看到JavaScript代码以这种方式检查未定义的参数等:

if (typeof input !== "undefined") {    // do stuff}

这似乎有点浪费,因为它涉及类型查找和字符串比较,更不用说它的冗长了。这是必需的,因为undefined可以重命名。

我的问题是:
与该方法相比,该代码有何优势:

if (null != input) {    // do stuff}

据我所知,您无法重新定义null,因此不会意外中断。并且,由于!=运算符的类型强制,这将同时检查undefinednull…,这通常正是您想要的(例如,用于可选功能参数)。

但是,这种形式似乎并不广泛,甚至会导致JSLint对使用邪恶!=运算符的人大吼大叫。

为什么认为这种风格不好?

答案1

小编典典

typeof 更安全,因为它允许从未声明过标识符:

if(typeof neverDeclared === "undefined") // no errorsif(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined

angular – 在typescript中定义typeof抽象类

angular – 在typescript中定义typeof抽象类

如何将typeList BaseListComponent设置为可分配?

下面的代码引发以下错误:

Type ‘({ title: string; component: typeof QuestionsListComponent;
} | { title: string; component: ...'
is not assignable to type '{
title: string; component: typeof BaseListComponent; }[]'
.

摘抄:

abstract class BaseListComponent {
  protected title
}

class WeatherListComponent extends BaseListComponent {}

class QuestionsListComponent extends BaseListComponent {}

let containerItems: Array<{title: string,component: typeof BaseListComponent}>;
containerItems = [
  {title:'TypeScript',component: QuestionsListComponent},{title:'Angular2',{title:'Weather',component: WeatherListComponent}
]

P.S这是一个角度应用的简化摘录,所以这种疯狂背后有逻辑.

解决方法

使用angular的 Type接口是解决方案.可以找到更好的解释什么类型是 here.要解决的步骤:

>导入类型如下:import @ Type} from“@ angular / core”;
>将Typeof BaseListComponent替换为Type< BaseListComponent>

对于那些不使用角度的人来说,this thread可能会有所帮助.

angularjs – TypeError:无法读取[null]中未定义的属性’post’

angularjs – TypeError:无法读取[null]中未定义的属性’post’

在我的Angular 2项目中,ListingService无法通过post从服务器获取数据.我收到这个错误:
EXCEPTION: TypeError: Cannot read property 'post' of undefined in [null]
ORIGINAL EXCEPTION: TypeError: Cannot read property 'post' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'post' of undefined
at ListingService.getListings (http://localhost:3000/app/listing.service.js:30:30)
at ListingsComponent.getListings (http://localhost:3000/app/listings.component.js:45:41)
at ListingsComponent.ngOnInit (http://localhost:3000/app/listings.component.js:41:26)
at AbstractChangeDetector.ChangeDetector_HostListingsComponent_0.detectChangesInRecordsInternal (eval at <anonymous> (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:10897:14),<anonymous>:22:99)
at AbstractChangeDetector.detectChangesInRecords (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8824:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8807:12)
at AbstractChangeDetector._detectChangesContentChildren (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8871:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8808:12)
at AbstractChangeDetector._detectChangesInViewChildren (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8877:14)
at AbstractChangeDetector.runDetectChanges (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8811:12)

我的ListingService.ts看起来像这样:

import {Injectable,Injector} from 'angular2/core';
import {HTTP_PROVIDERS,Http,Headers} from 'angular2/http';
import {Listing} from './listing';
import 'rxjs/add/operator/map';
@Injectable()
export class ListingService {
 http: Http;
 listings: Array<Listing>;
 getListings() {
    var headers = new Headers();
    headers.append('Content-Type','application/json');
    this.http.post('http://144.376.29.134:and-so-on',JSON.stringify(
    {"id":1,"title": "Title","description": "Проводите","discount": "21%","imageUrl": "http://lorempixel.com/400/200/sports","tags": [{"tag": "Еда"}]
    }),{headers:headers}
    ).map(res => res.json())
    .subscribe((res:Array<Listing>) => this.listings = res);
    return Promise.resolve(this.listings);
 }
 getListing(id: number) {
    return Promise.resolve(this.listings)
    .then(listings => listings.filter(l => l.id === id)[0]);
 }
}

使用ListingService的ListingsComponent如下所示:

import {Component,OnInit} from 'angular2/core';
import {HTTP_PROVIDERS,Headers} from 'angular2/http';
import {Listing} from './listing';
import {ListingService} from './listing.service';
import 'rxjs/add/operator/map';
@Component({
  ....
})
export class ListingsComponent implements OnInit {
 listings: Array<Listing>;
 constructor(private listingService:ListingService,private _router: Router) {}
 ngOnInit() {
  this.getListings();
 }
 getListings() {
  this.listingService.getListings().then(listings => this.listings = listings);
 }
 getListing(id: number) {
  return Promise.resolve(this.listings)
  .then(listings => listings.filter(l => l.id === id)[0]);
 }
 gotoDetail(listing: Listing) {
  this._router.navigate(['ListingDetail',{ id: listing.id }]);
 }
}

这有什么问题?

您必须将HTTP_PROVIDERS添加到组件提供程序数组,如下所示:
providers: [HTTP_PROVIDERS]

或者最好是在这样的引导程序中:

bootstrap(AppComponent,[HTTP_PROVIDERS]);

而且你在ListingService中缺少构造函数http注入:

export class ListingService {
   constructor(private http : Http){}
}

附录

您没有收到任何列表的原因是因为您使用的是Promise而不是Observable:

在ListingService中的getListings()中返回:

return this.http.post("bla bla").map(res => res.json).map((res) => {
    return this.listings = res;
});

然后在ListingsComponent的getListings()中订阅这个:

getListings() {
  this.listingService.getListings().subscribe(listings => this.listings = listings);
}

c# – typeof(DateTime?).Name == Nullable`1

c# – typeof(DateTime?).Name == Nullable`1

在.Net typeof(DateTime?)中使用Reflection.名称返回“Nullable`1”.

有没有办法将实际类型作为字符串返回. (在本例中为“DateTime”或“System.DateTime”)

我明白DateTime?是Nullable< DateTime>.除此之外,我只是在寻找可空类型的类型.

解决方法

在这种情况下,有一个 Nullable.GetUnderlyingType方法可以帮助您.可能你最终想要制作自己的实用工具方法,因为(我假设)你将使用可空和非可空类型:
public static string GetTypeName(Type type)
{
    var nullableType = Nullable.GetUnderlyingType(type);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType.Name;
    else
        return type.Name;
}

用法:

Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime"
Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"

编辑:我怀疑你也可能在类型上使用其他机制,在这种情况下,您可以稍微修改它以获取基础类型或使用现有类型,如果它不可为空:

public static Type GetNullableunderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType)
{
    var nullableType = Nullable.GetUnderlyingType(possiblyNullableType);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType;
    else
        return possiblyNullableType;
}

对于一种方法来说,这是一个可怕的名字,但我不够聪明,想出一个方法(如果有人建议更好的话,我会很乐意改变它!)

然后作为扩展方法,您的用法可能如下:

public static string GetTypeName(this Type type)
{
    return type.GetNullableunderlyingTypeOrTypeIfNonNullable().Name;
}

要么

typeof(DateTime?).GetNullableunderlyingTypeOrTypeIfNonNullable().Name

c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?

c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?

我正在看别人写的这段代码,我想知道它什么时候会评估为真.基本上,它说someType是someOtherType的一个实例.它甚至有意义吗?到目前为止,我已经尝试过:

derivedClass.GetType().isinstanceOfType(typeof(BaseClass)) 

baseClass.GetType().isinstanceOfType(typeof(DerivedClass)) 

myClass.GetType().isinstanceOfType(typeof(MyClass))

并且所有人都评价为假.

任何帮助表示赞赏.

解决方法

只有当涉及的对象(derivedClass,baseClass和myClass)是对象的实例或未记录的RuntimeType对象(注意 Type是抽象的)时,这3行中的每一行都将返回true,因此例如以下将导致true声明:

var myObject = new object();
myObject.GetType().isinstanceOfType(typeof(Console));

myObject = typeof(Object);
myObject.GetType().isinstanceOfType(typeof(Console));

请注意,使用的类型(在本例中为Console)无关紧要,并且对语句的结果没有影响.

为什么?

IsInstanceOfType的文档告诉我们,如果传入的对象是当前类型的实例,它将返回true,例如,如果myForm是一个派生自Form的类,则以下语句将返回true,否则它将返回false.

typeof(Form).isinstanceOfType(myForm);

在你的情况下,myForm实际上是typeof(BaseClass),它是未记录的类型RuntimeType(派生自Type),因此如果这个未记录的类型恰好从提供的类型派生,你只会返回true – 这是不太可能是理想的行为.

我应该用什么呢?

您可能会追溯的是is keword,如果提供的对象是给定类型的实例,则返回true

derivedClass is BaseClass
baseClass is DerivedClass
myClass is MyClass

关于typeof!==“未定义” vs. = nullc语言typeof未定义的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于angular – 在typescript中定义typeof抽象类、angularjs – TypeError:无法读取[null]中未定义的属性’post’、c# – typeof(DateTime?).Name == Nullable`1、c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?等相关知识的信息别忘了在本站进行查找喔。

本文标签: