有没有办法在C#中执行此操作而不为每个var类型设置重载的新方法?
$box = !empty($toy) : $toy ? "";
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是:
if (toy != null)
{
box += toy;
}
Run Code Online (Sandbox Code Playgroud)
或这个:
public string emptyFilter(string s) ...
public int emptyFilter(int i) ...
public bool emptyFilter(bool b) ...
public object emptyFilter(object o)
{
try
{
if (o != null)
{
return o.ToString();
}
else
{
return "";
}
}
catch (Exception ex)
{
return "exception thrown":
}
}
box += this.emptyFilter(toy);
Run Code Online (Sandbox Code Playgroud)
我基本上想检查以确保变量/属性设置/不为空/存在/有值/等等...并返回它或""没有一些像上面这样的代码的荒谬.
Dar*_*rov 18
您可以使用条件运算符(?:):
string box = (toy != null) ? toy.ToString() : "";
Run Code Online (Sandbox Code Playgroud)
Bra*_*tie 10
return variable ?? default_value;
Run Code Online (Sandbox Code Playgroud)
你想要的是什么?考虑到你正在展示PHP代码并使用C#标记它,我有点困惑.
还有Nullable<T>你可以使用的类型.
扩展课程怎么样?
public static class ToStringExtender
{
public static String ToStringExt(this Object myObj)
{
return myObj != null ? myObj.ToString() : String.Empty;
}
}
var myobject = foo.ToStringExt()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61745 次 |
| 最近记录: |