我的代码中有以下属性
public float X {
get {
if (parent != null)
return parent.X + position.X;
return position.X;
}
set { position.X = value; }
}
Run Code Online (Sandbox Code Playgroud)
我希望将吸气剂转换成形式
get {
return parent?.X + position.X;
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误: Cannot implicitly convert type 'float?' to 'float'. An explicit conversion exists (are you missing a cast?)
我做错了什么或现在不能用?
的类型 parent?.Xfloat?你要添加到是float- 导致另一个float?.这不能隐式转换为float.
虽然Yuval的答案应该有效,但我会亲自使用以下内容:
get
{
return (parent?.X ?? 0f) + position.X;
}
Run Code Online (Sandbox Code Playgroud)
要么
get
{
return (parent?.X).GetValueOrDefault() + position.X;
}
Run Code Online (Sandbox Code Playgroud)
我不确定你的设计,请注意 - 你在吸气器中添加东西而不是在设置器中添加东西的事实很奇怪.这意味着:
foo.X = foo.X;
Run Code Online (Sandbox Code Playgroud)
...如果parent非零X值且非零值,则不会是无操作.
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |