GVKun编程网logo

是否有JDK或Guava方法将null转换为空列表?(null java)

11

最近很多小伙伴都在问是否有JDK或Guava方法将null转换为空列表?和nulljava这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Angular2Webpacklazylo

最近很多小伙伴都在问是否有JDK或Guava方法将null转换为空列表?null java这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Angular2 Webpack lazyload TypeError:无法将undefined或null转换为object、c – 将nullptr转换为bool、c# – Mvc ViewBag – 无法将null转换为“bool”,因为它是不可为空的值类型、c# – 如何将Nullable DateTime变量的null值转换为DbNull.Value等相关知识,下面开始了哦!

本文目录一览:

是否有JDK或Guava方法将null转换为空列表?(null java)

是否有JDK或Guava方法将null转换为空列表?(null java)

JDK或Google Guava中是否有类似这种方法

public static <T> Collection<T> safe(Collection<T> collection) {    if (collection == null) {        return new ArrayList<>(0);    } else {        return collection;    }}

例如,如果某些东西返回空列表,这很容易在增强循环中不崩溃

for (String string : CollectionUtils.safe(foo.canReturnANullListOfStrings())) {    // do something}

不会崩溃。

我环顾四周,却找不到任何这样的方法,我想知道我是否错过了它,或者是否有这样的原因导致这种方便的方法不方便使用,因此不包括在内?

答案1

小编典典

Objects.firstNonNull(list, ImmutableList.of());

不需要专门的方法,实际上,这是我们建议的解决方案,建议您从顽皮的API中获取可能为空的集合时立即使用,理想情况下最好不要这样做。

Angular2 Webpack lazyload TypeError:无法将undefined或null转换为object

Angular2 Webpack lazyload TypeError:无法将undefined或null转换为object

我遇到角度路由器加载器的问题,
我想懒惰加载一个模块,我遵循我看到的每个指南,
并且我不断收到此错误:TypeError:无法将undefined或null转换为object:

The error

这是我的webpack.config.common.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        'app': './app/main.ts'
    },resolve: {
        extensions: ['.js','.ts']
    },module: {
        loaders: [
            {
                test: /\.ts$/,loaders: [
                    'awesome-typescript-loader','angular2-template-loader','angular-router-loader'
                ]
            },{
                test: /\.html$/,loader: 'html-loader'
            },{
                test: /\.css$/,loader: 'raw-loader'
            }
        ]
    },plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html'
        }),new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,'./app' // location of the src
        )
    ]
};

这是app.routing.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes,RouterModule } from '@angular/router';

const appRoutes: Routes = [
    {
        path: '',redirectTo: '/dashboard',pathMatch: 'full'
    },{
        path: 'dashboard',loadChildren: './dashboard/dashboard.module#DashboardModule'
    }
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

这是仪表板/仪表板.模块:

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { FormsModule }    from '@angular/forms';

import { DashboardComponent }    from './dashboard.component';

import { dashboardRouting } from './dashboard.routing';

@NgModule({
    imports: [
        CommonModule,FormsModule,dashboardRouting
    ],declarations: [
        DashboardComponent
    ],providers: [
    ]
})
export class DashboardModule {}

这是我的依赖项:

"devDependencies": {
    "@types/core-js": "^0.9.35","@types/hammerjs": "^2.0.34","@types/jasmine": "^2.5.38","@types/node": "^6.0.53","angular-router-loader": "^0.5.0","angular2-template-loader": "^0.6.0","awesome-typescript-loader": "^3.0.0-beta.18","del-cli": "^0.2.1","html-loader": "^0.4.4","html-webpack-plugin": "^2.26.0","lite-server": "^2.2.2","raw-loader": "^0.5.1","webpack": "^2.2.0-rc.4","webpack-dev-server": "^2.2.0-rc.0","webpack-merge": "^2.4.0"
  }

我做错了什么?

解决方法

尝试导入

import { RouterModule } from '@angular/router';
import { <children routes of dashboard> } from '<path of dashboard child routes>';

在您的仪表板/ dashboard.module中,然后将其放在DashboardModule的NgModule导入区域中

@NgModule({
    imports: [
        CommonModule,imports: [
        RouterModule.forChild(<children routes of dashboard>)
    ]
})
export class DashboardModule {}

请替换<>部分有必要的细节.

c – 将nullptr转换为bool

c – 将nullptr转换为bool

在C前11天,写作被认为是更好的做法:

if (ptr == NULL)

而不是:

if (!ptr)

这有两个原因.它效率更高,因为它不需要强制转换为bool.并且无法保证宏NULL确实会评估为布尔值false.在C 11中这仍然是真的吗?写作是否更可取

if (ptr == nullptr)

而不是

if (!ptr)

或者现在是第二次罚款?

解决方法

It is more efficient because it didn’t need to cast to bool.

我打了一个ol'[引证需要].我怀疑任何现代编译器都能算得上.

if(ptr)是完全正确的,并且可能在语义上更正确,如果你使用该值来表示规范的“缺乏价值”.

我只期望看看(ptr!= nullptr)是否有人实际上使用“null”值进行指针算术,但即使这样,它也是非常粗略的.

话虽这么说,很多时候你可以逃脱…根本没有检查.如果指针的可空性用于表示可为空的数据字段,请使用optional.如果您正在初始化它以防它为空,请使用value_or idiom.如果它只是一个弱参考而且价值合约在外面,那么断言就可以了.

c# – Mvc ViewBag – 无法将null转换为“bool”,因为它是不可为空的值类型

c# – Mvc ViewBag – 无法将null转换为“bool”,因为它是不可为空的值类型

我想在控制器中将bool设置为true,当产生某个视图,然后相应地更改视图的标题.这应该是死的简单,而是我得到:

Cannot perform runtime binding on a null reference Exception Details:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform
runtime binding on a null reference

所有Im在控制器中:

[AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.IsRegistration = true;
            return View();
        }

然后在视图中:

@if (ViewBag.IsRegistration)
        {
        <legend>Register using another service.</legend>
        }
        else
        {
        <legend>Use another service to log in.</legend>
        }

但它失败了:

@if (ViewBag.IsRegistration)

UPDATE

相关控制器代码:

[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.IsRegistration = "true";
    return View();
}

注册视图:

@model Mvc.Models.Registerviewmodel
@{
    Layout = "~/Views/Shared/_AccountLayout.cshtml";
    ViewBag.Title = "Register";
}

<hgroup>
    <h1>@ViewBag.Title.</h1>
</hgroup>

<div>
<div>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        <fieldset>
            <legend>Create a new account.</legend>
            <div>
                @Html.LabelFor(m => m.UserName,new { @})
                <div>
                    @Html.TextBoxFor(m => m.UserName)
                </div>
            </div>
            <div>
                @Html.LabelFor(m => m.Password,new { @})
                <div>
                    @Html.PasswordFor(m => m.Password)
                </div>
            </div>
            <div>
                @Html.LabelFor(m => m.ConfirmPassword,new { @})
                <div>
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </div>
            </div>
            <div>
                <input type="submit" value="Register"/>
            </div>
        </fieldset>
    }
</div>
    <div></div>
  <section id="socialLoginForm">
            @Html.Action("ExternalLoginsList",new { ReturnUrl = ViewBag.ReturnUrl })
        </section>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

ExternalLoginsList partial:

@using Glimpse.Core.Extensions
@using Microsoft.Owin.Security
@model ICollection<AuthenticationDescription>

@if (Model.Count == 0)
{
    <div>
        <p>There are no external authentication services configured</p>
    </div>
}
else
{
    using (Html.BeginForm("ExternalLogin","Account",new { ReturnUrl = ViewBag.ReturnUrl }))
    {
    @Html.AntiForgeryToken()

        <fieldset id="socialLoginList">
            @if (!string.IsNullOrEmpty(ViewBag.IsRegistration))
            {
            <legend>Register using another service.</legend>
            }
            else
            {
            <legend>Use another service to log in.</legend>
            }
            <p>
                @foreach (AuthenticationDescription p in Model) {
                    <button type="submit"id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.AuthenticationType</button>
                }
            </p>
        </fieldset>
    }
}

解决方法

尝试:
@if (ViewBag.IsRegistration == true)

c# – 如何将Nullable DateTime变量的null值转换为DbNull.Value

c# – 如何将Nullable DateTime变量的null值转换为DbNull.Value

我有一个可以为空的DateTime变量.我想把它写到sql DB.当我尝试插入时:

如果变量有值,则没有问题.

但如果它没有值,则插入中断错误.

我想问:我们如何通过DbCommand参数将可空的DateTime插入sql?

(P.S.:sql列也可以为空.)

DateTime? myDate = null;
DbCommand dbCommand = new DbCommand();
dbCommand.Parameters.Add("NullablesqlDateField",DbType.DateTime,myDate);

解决方法

试试 null coalescing operator:

dbCommand.Parameters.Add("NullablesqlDateField",(object) myDate ?? dbnull.Value);

我们今天的关于是否有JDK或Guava方法将null转换为空列表?null java的分享就到这里,谢谢您的阅读,如果想了解更多关于Angular2 Webpack lazyload TypeError:无法将undefined或null转换为object、c – 将nullptr转换为bool、c# – Mvc ViewBag – 无法将null转换为“bool”,因为它是不可为空的值类型、c# – 如何将Nullable DateTime变量的null值转换为DbNull.Value的相关信息,可以在本站进行搜索。

本文标签: