类似的代码在 kotlin 中运行良好,但在 C# 中不起作用
public static class Helper
{
public static T RequireNotNll<T>(T? obj,string? message) {
if (obj == null) {
throw new Exception(message ?? "obj must not null");
}
return obj;
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙
dynamic飞镖和Object?飞镖有什么区别吗?
这个问题听起来可能与What is the Difference betweendynamic and Object in dart?重复。。然而,我认为并非如此。我不是在谈论语义差异或 dart 分析器抛出的任何警告,或从编码员的角度来看的任何内容。我想知道两者之间是否存在真正的区别。
我可以为两者分配任何数据值。
当我运行以下命令时:
Object? a;
dynamic b;
print(a.runtimeType);
print(b.runtimeType);
Run Code Online (Sandbox Code Playgroud)
我得到:
Null
Null
Run Code Online (Sandbox Code Playgroud)
我知道dynamic是一个关键字,而Object?是一个对象类。但确实dynamic推断Object?.
我是 Dart lang 的新手。所以,请赐教。
我正在编写使用使用Optionals 的 Java 库的 Kotlin 代码,并且我更愿意在 Kotlin 世界中使用 Kotlin 的可空习惯用法。
例如,我的图书馆可能有一个功能
Optional<Foo> getFoo(String fooId) {
...
}
Run Code Online (Sandbox Code Playgroud)
在我的 Kotlin 程序中我想
foo: Foo? = /* something, something */ getFoo(fooId)
Run Code Online (Sandbox Code Playgroud)
我知道我可以做类似的事情
lateinit var foo: Foo?
val fooOpt = getFoo(fooId)
if(fooOpt.isPresent) foo = fooOpt.get()
else foo = null
Run Code Online (Sandbox Code Playgroud)
但是,鉴于 Java 的Optional用途与可空值几乎相同,这似乎不必要地冗长,即使我将其折叠为
val foo: Foo? = getFoo(fooId).orElse(null)
Run Code Online (Sandbox Code Playgroud) 对Kotlin来说相当新 - 我有点困惑为什么在这个例子中使用let时'它'仍然可以为空?结果,该示例无法编译
错误:(9,20)类型不匹配:推断类型是Int?但Int是预料之中的
fun main(args: Array<String>) {
val myNewNullableInt: Int? =6
myNewNullableInt.let{
printAnInteger(it)
}
}
fun printAnInteger (integerToPrint: Int){
println(integerToPrint)
}
Run Code Online (Sandbox Code Playgroud)
示例:https: //try.kotlinlang.org/#/UserProjects/fnlicstrn4tbmk8gs071vmv4ka/9dd72cr92ikggh3g9qg981h01o
我正在尝试使用ILGPU来扰乱我的GPU上的CUDA。
当我尝试加载内核并向其传递一些数据时:
var krnl = gpu.LoadAutoGroupedStreamKernel<Index1, ArrayView<byte>, int[]>(krnCopyStringToCard);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误,这确实令人困惑:
类型“int[]”必须是不可为 null 的值类型才能将其用作参数...
查看可为空的文档(对我来说是新的),似乎int 可以为空,但前提是您如此声明。我绝对不会这样做,那有什么用呢?
这些运算符有什么区别?
var c = foo?.Prop1;
Run Code Online (Sandbox Code Playgroud)
var c = foo!.Prop1;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,Prop1是一个int.
我正在与一个公开以下功能的API接口:
IEnumerable<Color?> getColors(long Id);
Run Code Online (Sandbox Code Playgroud)
我调用该函数:
IEnumerable<System.Drawing.Color?> colList = getColors(1);
Run Code Online (Sandbox Code Playgroud)
函数返回时,列表不为null。但是,当我尝试遍历列表时:
foreach (System.Drawing.Color col in colList)
{...}
Run Code Online (Sandbox Code Playgroud)
我什么都没有。没有进入循环。
遍历列表的正确方法是什么?
编辑:我终于想出了如何用这个伏都教得到一个列表计数:
int colCount = colList.Count<System.Drawing.Color?>();
Run Code Online (Sandbox Code Playgroud)
正如建议的那样,该计数确实为零。我现在向API提供者询问为什么这样做?
感谢所有提供正面和建设性建议的人。
我知道n.HasValue && n.Value > 0但真的很想测试空值,所以:
decimal? n = null;
Console.Write(n>0); // false
Console.Write(n<0); // false
Run Code Online (Sandbox Code Playgroud)
那么nullC# 中的对象是正数还是负数?