- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 C# 中使用新的可为空引用类型。很高兴看到他们从 Swift 中挖走了这个!这是一个非常棒的功能!但是...因为它本质上是“固定在”语言上的,所以我正在努力创建一个泛型,它可以采用任何可空类型,无论是值还是引用,这在 Swift 中都是微不足道的。
考虑这个类:
public abstract class LabeledValue<TValue> {
public string? label { get; set; }
public TValue? value { get; set; }
}
Int
以一个名为“Foo”的类为例:
public class LabeledInt : LabeledValue<Int>{}
var myLabeledIntA = new LabeledInt(){
label = "Forty Four",
value = 44
}
var myLabeledIntB = new LabeledInt(){
label = "Not Set",
value = null
}
public class LabeledFoo : LabeledValue<Foo>{}
var myLabeledFooA = new LabeledFoo(){
label = "Set",
value = new Foo()
}
var myLabeledFooB = new LabeledFoo(){
label = "Not Set",
value = null
}
public abstract class LabeledValue<TValue>
where TValue : Nullable {
public string? label { get; set; }
public TValue? value { get; set; }
}
public abstract class LabeledValue<TValue>
where TValue : struct {
public string? label { get; set; }
public TValue? value { get; set; }
}
public abstract class LabeledValue<TValue> {
public string? label { get; set; }
public Nullable<TValue> value { get; set; }
}
public abstract class LabeledValue<TValue> {
public string? label { get; set; }
public TValue value { get; set; }
}
public class LabeledInt : LabeledValue<Int?>{}
最佳答案
好的,找到了。您必须使用两个新的显式属性,AllowNull
和 MaybeNull
.
这是修改后的代码...
public abstract class LabeledValue<TValue> {
public string? label { get; set; }
[AllowNull, MaybeNull]
public TValue value { get; set; }
}
public class LabeledInt : LabeledValue<int>{}
public class LabeledNInt : LabeledValue<int?>{}
public class LabeledFoo : LabeledValue<Foo>{}
public class LabeledNFoo : LabeledValue<Foo?>{}
var a = new LabeledInt();
a.Value = 4;
a.value = null // This won't compile
var b = new LabeledNInt();
b.Value = 4;
b.Value = null; // This compiles just fine
var c = new LabeledFoo();
c.Value = new Foo();
c.Value = null; // This won't compile
var d = new LabeledNFoo();
d.Value = new Foo();
d.Value = null; // This compiles just fine
Note: There is still a warning about
Value
being uninitialized, but it's only a warning, not an error. You have to make sure to explicitly setValue
for non-null types before accessing it. Kind of defeats the purpose of using nullable/non-nullable types, but this is more a hack than a true solution which isn't actually possible since nullable value types are really the concreteNullable<T>
whereas nullable reference types are regular reference types just adorned with an attribute to let the compiler know not to accept nulls.
关于c# - 你能定义一个接受*任何*可为空的类型、值或引用的泛型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59739194/
我是一名优秀的程序员,十分优秀!