我有一个WCF数据契约与一堆原始类型的属性,如int和decimal,DateTime(当然,这是一个结构).
我的同事建议将它们全部为可空,然后通过检查null来验证服务端的必需值.我相信部分原因是因为它是一个可序列化的对象,所以你不能用数据契约上的构造函数强制执行所需的值 - 它避免了测试默认值的麻烦.
但是,我还希望在合同中隐含必需的属性,以便客户可以了解所需的属性.
所以不要做类似的事情,
[DataMember]
public Nullable<int> AgencyID { get; set; }
Run Code Online (Sandbox Code Playgroud)
这将允许我在服务端干净地测试null,我这样做:
[DataMember(IsRequired = true, EmitDefaultValue = true)]
public int AgencyID { get; set; }
Run Code Online (Sandbox Code Playgroud)
我的理解是,如果没有为属性分配值或者默认值为0,这将抛出异常 - 这是所需的行为.这是在客户端执行所需属性的最佳实践吗?让一切都可以为空并在服务端检查它有什么好处吗?
我正在使用注释来确保参数不为null,假设这会导致编译器检查.
public @Nullable ApplicationAccount accountForKey(@NonNull String key) {
return accounts.get(key);
}
Run Code Online (Sandbox Code Playgroud)
但是,通过运行此代码,我在此行上得到了NullPointerException
java.util.concurrent.ConcurrentHashMap.get (ConcurrentHashMap.java:883)
Run Code Online (Sandbox Code Playgroud)
那么注释有什么意义呢?
如果我像这样写额外的支票,那就更加模糊了
return key!=null?accounts.get(key):null;
Run Code Online (Sandbox Code Playgroud)
Android Studio警告我,检查没用!
更新:完整调用堆栈:
Caused by java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:883)
at co.getcontrol.services.MerchantCenter.accountForKey(MerchantCenter.java:72)
at co.getcontrol.model.customers.CustomersAggregator.loadCustomerDetails(CustomersAggregator.java:91)
at co.getcontrol.model.customers.CustomerDetailsPresenter.callData(CustomerDetailsPresenter.java:39)
at co.getcontrol.reskin.ui.customers.CustomerDetailsViewFragment.onCreateView(CustomerDetailsViewFragment.java:152)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
at co.getcontrol.ui.ControlActivity.onStart(ControlActivity.java:13)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5353)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2352)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(NativeStart.java)
Run Code Online (Sandbox Code Playgroud) java android nullpointerexception non-nullable android-annotations
快速Kotlin最佳实践问题,因为我无法从文档中找到最佳方法.
假设我有以下嵌套映射(为此问题的目的明确指定键入):
val userWidgetCount: Map<String, Map<String, Int>> = mapOf(
"rikbrown" to mapOf(
"widgetTypeA" to 1,
"widgetTypeB" to 2))
Run Code Online (Sandbox Code Playgroud)
以下模式可以更简洁吗?
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username]?.get(widgetType)?:0
}
Run Code Online (Sandbox Code Playgroud)
换句话说,如果用户已知并且他们有该窗口小部件类型的条目,我想返回用户窗口小部件计数,否则为零.特别是我看到我[]最初可以使用语法来访问地图,但是在使用之后我无法在第二级看到这样做的方法?..
num 在设置时应该可以为空,但它返回的内容应该始终是不可为空的(具有默认值).
class Test {
var num: Int? = null
get() = field ?: 5 // default value if null
}
Run Code Online (Sandbox Code Playgroud)
以下版本不编译,即使返回的值始终为非null,这对我来说是有意义的,因为类型不是推断的,而是来自支持字段:
val a: Int = Test().num
Run Code Online (Sandbox Code Playgroud)
类型不匹配:推断类型是Int?但Int是预料之中的
问题是如何将该getter的返回类型更改为不可为空?如果我这样做,编译器会说:
Getter返回类型必须等于属性的类型,即'Int?'
我知道我可以用另一个属性解决它numNotNullable(没有后备字段).
class Test {
var num: Int? = null
get() = field ?: 5 // default value if null
val numNotNullable: Int
get() = num ?: 5
}
val c: Int = Test().numNotNullable
Run Code Online (Sandbox Code Playgroud)
但这不是我想要的.还有另外一种方法吗?
我最近一直在看DbC和Spec#似乎支持非可空对象.不幸的是,Spec#似乎已被抛弃.
我没有看到在语言中内置这样的功能的问题.有人能开导我吗?
我当前正在尝试将新的C#8.0非空引用类型功能应用于现有代码,并且不知道如何在以下数据反序列化方法中解决CS8603警告:
T ReadOptional<T>() where T : IEntity, new()
{
if (ReadBoolean())
{
T instance = new T();
instance.Read(this); // IEntity method
return instance;
}
else
{
// CS8603 Possible null reference return.
return default;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,如果前面的布尔值为false,则该方法可能返回null(classes)/ default(structs),否则它将返回一个T实例,该实例可以是任何实现的IEntity。
但是,我不能将返回类型标记为T?,因为null如果T是struct,它实际上不会返回,如编译器错误CS8627正确抱怨的那样:
// CS8627: A nullable type parameter must be known to be a value type or non-nullable
// reference type. Consider adding a 'class', 'struct', or type constraint.
T? …Run Code Online (Sandbox Code Playgroud) 该帖子专门针对C#8。让我们假设我要使用此方法:
public static TValue Get<TKey, TValue>(
this Dictionary<TKey, TValue> src,
TKey key, TValue @default)
=> src.TryGetValue(key, out var value) ? value : @default;
Run Code Online (Sandbox Code Playgroud)
如果我的.csproj如下所示(即启用了C#8和可为空的类型,则所有警告均为错误):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>8</LangVersion>
<Nullable>enable</Nullable>
<WarningsAsErrors>true</WarningsAsErrors>
</PropertyGroup>
...
Run Code Online (Sandbox Code Playgroud)
此代码将产生以下构建时错误:
DictionaryEx.cs(28, 78): [CS8714] The type 'TKey' cannot
be used as type parameter 'TKey' in the generic type or
method 'Dictionary<TKey, TValue>'. Nullability of type argument
'TKey' doesn't match 'notnull' constraint.
Run Code Online (Sandbox Code Playgroud)
有什么方法可以指定TKey必须为非空类型?
给定一些可为空的类型T?,如何获得相应的不可为空的类型T?
例如:
T? x<T extends int?>(T? value) => value;
Type g<T>(T Function(T) t) => T;
Type type = g(x);
print(type); // Prints "int?"
Run Code Online (Sandbox Code Playgroud)
现在我想获得不可为空的类型。我如何创建该函数convert以便:
Type nonNullableType = convert(type);
print(nonNullableType); // Prints "int"
Run Code Online (Sandbox Code Playgroud) 我正在关注一个 Flutter 教程,其中包含以下代码,但代码在我的计算机上不起作用,而且我不知道如何修复它:
import 'package:flutter/foundation.dart';
class CartItem {
final String id;
CartItem({
@required this.id,
});
}
Run Code Online (Sandbox Code Playgroud)
但我收到这样的错误:
The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
{String id}
Run Code Online (Sandbox Code Playgroud) 是否可以记录返回值不是nullJava 的Optional?
大多数工具和框架只关心参数,但我想用返回值不是的类型来表达null(而不是在 JavaDoc 中这样做)。
UPDATE Looks line 你可以同意团队使用Optional作为返回值,如果你想表达可能null和直接的对象,当它绝对不为空时:
public Optional<Job> getJob() { ... }
public Job extractJob(NonNullJobHolder<Job> holder) { ... }
Run Code Online (Sandbox Code Playgroud)